本文共 14092 字,大约阅读时间需要 46 分钟。
举个栗子,获取新闻详情的案例。
public ActionResult NewsView(int newsId){ var news = _newsService.GetNewsById(newsId); // 获取数据 NewsModel newsItem = new NewsModel(); // 新建模型存储数据 if (null != news) { newsItem.Id = news.Id; newsItem.Title = news.Title; newsItem.Short = news.Short; newsItem.Full = news.Full; newsItem.AllowComments = news.AllowComments; newsItem.CommentCount = news.CommentCount; newsItem.PrizeCount = news.PrizeCount; newsItem.ClickCount = news.ClickCount + 1; newsItem.CreatedOn = news.CreatedOn.ToString("yyyy-MM-dd HH:mm:ss"); // 处理日期 newsItem.IsPrize = null != news.NewsComments.FirstOrDefault(m => m.IsPrize); if (news.NewsPictures.Count > 0) // 处理新闻图片 { foreach (var itemp in news.NewsPictures.OrderBy(m => m.DisplayOrder)) { newsItem.CoverImgUrls.Add(_pictureService.GetPictureUrl(itemp.PictureId)); } } news.ClickCount++; _newsService.UpdateNews(news); // 更新点击数量 } return View(newsItem); // 将数据传入界面端}
再谈_newsService如何获取数据。
using Nop.Core;using Nop.Core.Data;using Nop.Core.Domain.News;using Nop.Services.Events;using System;using System.Collections.Generic;using System.Linq;namespace Nop.Services.News{ ////// News service /// public partial class NewsService : INewsService { #region Fields private readonly IRepository_newsItemRepository; private readonly IRepository _newsCommentRepository; private readonly IRepository _newsPictureRepository; private readonly IEventPublisher _eventPublisher; #endregion #region Ctor public NewsService(IRepository newsItemRepository, IRepository newsCommentRepository, IRepository newsPictureRepository, IEventPublisher eventPublisher) { this._newsItemRepository = newsItemRepository; this._newsCommentRepository = newsCommentRepository; this._newsPictureRepository = newsPictureRepository; this._eventPublisher = eventPublisher; } #endregion #region Methods /// /// Deletes a news /// /// News item public virtual void DeleteNews(NewsItem newsItem) { if (newsItem == null) throw new ArgumentNullException("newsItem"); _newsItemRepository.Delete(newsItem); //event notification _eventPublisher.EntityDeleted(newsItem); } ////// Gets a news /// /// The news identifier ///News public virtual NewsItem GetNewsById(int newsId) { if (newsId == 0) return null; return _newsItemRepository.GetById(newsId); } ////// Gets all news /// /// Language identifier; 0 if you want to get all records /// Store identifier; 0 if you want to get all records /// Page index /// Page size /// A value indicating whether to show hidden records ///News items public virtual IPagedListGetAllNews(int languageId = 0, int storeId = 0, int pageIndex = 0, int pageSize = int.MaxValue, bool showHidden = false) { var query = _newsItemRepository.Table; if (!showHidden) { query = query.Where(n => n.Published); } query = query.OrderByDescending(n => n.CreatedOn); var news = new PagedList (query, pageIndex, pageSize); return news; } /// /// Inserts a news item /// /// News item public virtual void InsertNews(NewsItem news) { if (news == null) throw new ArgumentNullException("news"); _newsItemRepository.Insert(news); //event notification _eventPublisher.EntityInserted(news); } ////// Updates the news item /// /// News item public virtual void UpdateNews(NewsItem news) { if (news == null) throw new ArgumentNullException("news"); _newsItemRepository.Update(news); //event notification _eventPublisher.EntityUpdated(news); } ////// Gets news /// /// The news identifiers ///News public virtual IListGetNewsByIds(int[] newsIds) { var query = _newsItemRepository.Table; return query.Where(p => newsIds.Contains(p.Id)).ToList(); } /// /// Gets all comments /// /// Customer identifier; 0 to load all records ///Comments public virtual IListGetAllComments(int customerId) { var query = from c in _newsCommentRepository.Table orderby c.CreatedOn where (customerId == 0 || c.CustomerId == customerId) select c; var content = query.ToList(); return content; } /// /// Gets a news comment /// /// News comment identifier ///News comment public virtual NewsComment GetNewsCommentById(int newsCommentId) { if (newsCommentId == 0) return null; return _newsCommentRepository.GetById(newsCommentId); } ////// Get news comments by identifiers /// /// News comment identifiers ///News comments public virtual IListGetNewsCommentsByIds(int[] commentIds) { if (commentIds == null || commentIds.Length == 0) return new List (); var query = from nc in _newsCommentRepository.Table where commentIds.Contains(nc.Id) select nc; var comments = query.ToList(); //sort by passed identifiers var sortedComments = new List (); foreach (int id in commentIds) { var comment = comments.Find(x => x.Id == id); if (comment != null) sortedComments.Add(comment); } return sortedComments; } /// /// Deletes a news comments /// /// News comments public virtual void DeleteNewsComments(IListnewsComments) { if (newsComments == null) throw new ArgumentNullException("newsComments"); _newsCommentRepository.Delete(newsComments); } /// /// 更新新闻评论 /// /// public virtual void UpdateNewsComment(NewsComment newsComment) { if (newsComment == null) throw new ArgumentNullException("newsComment"); _newsCommentRepository.Update(newsComment); //event notification _eventPublisher.EntityUpdated(newsComment); } ////// Deletes a news comment /// /// News comment public virtual void DeleteNewsComment(NewsComment newsComment) { if (newsComment == null) throw new ArgumentNullException("newsComment"); _newsCommentRepository.Delete(newsComment); } public virtual IListGetNewsByCategoryId(int categoryId, int pageSize = 4) { var query = (from x in _newsItemRepository.Table where x.NewsCategoryId == categoryId && x.Published orderby x.CreatedOn descending select x).Take(pageSize).ToList(); return query; } public virtual PagedList GetNewsCommentsByNewsId(int newsId, int pageIndex = 1, int pageSize = 5) { var query = from x in _newsCommentRepository.Table where x.NewsItemId == newsId && !x.IsScreen && !x.IsPrize orderby x.CreatedOn descending select x; return new PagedList (query, pageIndex - 1, pageSize); } public virtual void ChangePrize(int newsId, int customerId, bool isPrize = true) { var news = GetNewsById(newsId); if (null != news) { var comments = (from x in news.NewsComments where x.NewsItemId == newsId && x.CustomerId == customerId && x.IsPrize orderby x.CreatedOn descending select x).FirstOrDefault(); if (isPrize) { if (null == comments) { news.NewsComments.Add(new NewsComment { NewsItemId = newsId, CustomerId = customerId, CreatedOn = DateTime.Now, IsPrize = true }); news.PrizeCount++; } } else { if (null != comments) { //news.NewsComments.Remove(comments); DeleteNewsComment(comments); news.PrizeCount--; } } UpdateNews(news); } } public virtual bool AddNewsComment(int newsId, int customerId, string text, out string msg) { bool result = false; var news = GetNewsById(newsId); if (null != news) { var comments = (from x in news.NewsComments where x.CustomerId == customerId && !x.IsPrize orderby x.CreatedOn descending select x).FirstOrDefault(); if (null != comments && comments.CreatedOn > DateTime.Now.AddMinutes(-1)) msg = "评论过于频繁"; else { news.NewsComments.Add(new NewsComment { NewsItemId = newsId, CustomerId = customerId, CommentText = text, CreatedOn = DateTime.Now, IsPrize = false, IsScreen=true }); msg = "评论成功,等待审核"; result = true; news.CommentCount++; UpdateNews(news); } } else { msg = "新闻不存在"; result = false; } return result; } /// /// 搜索所有的新闻 /// /// /// /// /// /// ///public virtual IPagedList GetAllNews(DateTime? dateFrom = null, DateTime? dateTo = null, int pageIndex = 0, int pageSize = int.MaxValue, bool showHidden = false) { var query = _newsItemRepository.Table; if (dateFrom.HasValue) query = query.Where(c => dateFrom.Value <= c.CreatedOn); if (dateTo.HasValue) query = query.Where(c => dateTo.Value >= c.CreatedOn); if (!showHidden) { query = query.Where(n => n.Published); } query = query.OrderByDescending(n => n.CreatedOn); var news = new PagedList (query, pageIndex, pageSize); return news; } /// /// 搜索所有的新闻评论 /// /// /// /// /// /// ///public virtual IPagedList GetAllComments(string commentContent=null,int pageIndex = 0, int pageSize = int.MaxValue) { var query = from c in _newsCommentRepository.Table where (!string.IsNullOrEmpty(commentContent)&&c.CommentText.Contains(commentContent.Trim()))||(string.IsNullOrEmpty(commentContent)) orderby c.Id descending select c; //if (!showHidden) //{ // query = query.Where(n => n.Published); //} return new PagedList (query, pageIndex, pageSize); } #region News pictures /// /// Deletes a news picture /// /// News picture public virtual void DeleteNewsPicture(NewsPicture newsPicture) { if (newsPicture == null) throw new ArgumentNullException("newsPicture"); _newsPictureRepository.Delete(newsPicture); //event notification _eventPublisher.EntityDeleted(newsPicture); } ////// Gets a news pictures by newsItem identifier /// /// The news identifier ///News pictures public virtual IListGetNewsPicturesByNewsItemId(int newsItemId) { var query = from np in _newsPictureRepository.Table where np.NewsItemId == newsItemId orderby np.DisplayOrder select np; var newsItemPictures = query.ToList(); return newsItemPictures; } /// /// Gets a newsItem picture /// /// News picture identifier ///News picture public virtual NewsPicture GetNewsPictureById(int newsPictureId) { if (newsPictureId == 0) return null; return _newsPictureRepository.GetById(newsPictureId); } ////// Inserts a newsItem picture /// /// News picture public virtual void InsertNewsPicture(NewsPicture newsPicture) { if (newsPicture == null) throw new ArgumentNullException("newsPicture"); _newsPictureRepository.Insert(newsPicture); //event notification _eventPublisher.EntityInserted(newsPicture); } ////// Updates a newsItem picture /// /// News picture public virtual void UpdateNewsPicture(NewsPicture newsPicture) { if (newsPicture == null) throw new ArgumentNullException("newsPicture"); _newsPictureRepository.Update(newsPicture); //event notification _eventPublisher.EntityUpdated(newsPicture); } ////// Get the IDs of all newsItem images /// /// News IDs ///All picture identifiers grouped by newsItem ID public IDictionaryGetNewsItemsImagesIds(int[] newsItemsIds) { return _newsPictureRepository.Table.Where(p => newsItemsIds.Contains(p.NewsItemId)) .GroupBy(p => p.NewsItemId).ToDictionary(p => p.Key, p => p.Select(p1 => p1.PictureId).ToArray()); } #endregion #endregion }}
这上面都是自己写的一些常用的数据库交互方法。
系统最核心的还是它! ##IRepository
using System.Collections.Generic;using System.Linq;namespace Nop.Core.Data{ ////// Repository /// public partial interface IRepositorywhere T : BaseEntity { /// /// Get entity by identifier /// /// Identifier ///Entity T GetById(object id); ////// Insert entity /// /// Entity void Insert(T entity); ////// Insert entities /// /// Entities void Insert(IEnumerableentities); /// /// Update entity /// /// Entity void Update(T entity); ////// Update entities /// /// Entities void Update(IEnumerableentities); /// /// Delete entity /// /// Entity void Delete(T entity); ////// Delete entities /// /// Entities void Delete(IEnumerableentities); /// /// Gets a table /// IQueryableTable { get; } /// /// Gets a table with "no tracking" enabled (EF feature) Use it only when you load record(s) only for read-only operations /// IQueryableTableNoTracking { get; } }}
为了处理,获取的数据,还需要定义个常用的Model模型来存储数据,这个真心的蛋疼。
using Nop.Web.Framework.Mvc;using System;using System.Collections.Generic;using System.Linq;using System.Web;namespace Nop.Web.Models.News{ public partial class AppNewsModel { public AppNewsModel() { this.News = new List(); } public bool result { get; set; } public string msg { get; set; } public List News { get; set; } } /// /// 新闻 /// public partial class NewsModel : BaseNopEntityModel { public NewsModel() { this.CoverImgUrls = new List(); } /// /// 标题 /// public string Title { get; set; } ////// 概要 /// public string Short { get; set; } ////// 详情(新闻列表不传该字段) /// public string Full { get; set; } ////// 允许评论 /// public bool AllowComments { get; set; } ////// 评论量 /// public int CommentCount { get; set; } ////// 点赞量 /// public int PrizeCount { get; set; } ////// 创建时间 /// public string CreatedOn { get; set; } ////// 赞 /// public bool IsPrize { get; set; } ////// 点击数量 /// public int ClickCount { get; set; } public ListCoverImgUrls { get; set; } }}
基本上,还是很清晰的。就跟王者荣耀游戏一样,玩几局,就摸透了。
F12定位恒好用。本文转自TBHacker博客园博客,原文链接:http://www.cnblogs.com/jiqing9006/p/6868169.html,如需转载请自行联系原作者