浅析.Net数据操作机制

简介:

举个栗子,获取新闻详情的案例。

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
{
    /// <summary>
    /// News service
    /// </summary>
    public partial class NewsService : INewsService
    {
        #region Fields
        private readonly IRepository<NewsItem> _newsItemRepository;
        private readonly IRepository<NewsComment> _newsCommentRepository;
        private readonly IRepository<NewsPicture> _newsPictureRepository;
        private readonly IEventPublisher _eventPublisher;

        #endregion

        #region Ctor

        public NewsService(IRepository<NewsItem> newsItemRepository,
            IRepository<NewsComment> newsCommentRepository,
            IRepository<NewsPicture> newsPictureRepository,
            IEventPublisher eventPublisher)
        {
            this._newsItemRepository = newsItemRepository;
            this._newsCommentRepository = newsCommentRepository;
            this._newsPictureRepository = newsPictureRepository;
            this._eventPublisher = eventPublisher;
        }

        #endregion

        #region Methods

        /// <summary>
        /// Deletes a news
        /// </summary>
        /// <param name="newsItem">News item</param>
        public virtual void DeleteNews(NewsItem newsItem)
        {
            if (newsItem == null)
                throw new ArgumentNullException("newsItem");

            _newsItemRepository.Delete(newsItem);

            //event notification
            _eventPublisher.EntityDeleted(newsItem);
        }

        /// <summary>
        /// Gets a news
        /// </summary>
        /// <param name="newsId">The news identifier</param>
        /// <returns>News</returns>
        public virtual NewsItem GetNewsById(int newsId)
        {
            if (newsId == 0)
                return null;

            return _newsItemRepository.GetById(newsId);
        }

        /// <summary>
        /// Gets all news
        /// </summary>
        /// <param name="languageId">Language identifier; 0 if you want to get all records</param>
        /// <param name="storeId">Store identifier; 0 if you want to get all records</param>
        /// <param name="pageIndex">Page index</param>
        /// <param name="pageSize">Page size</param>
        /// <param name="showHidden">A value indicating whether to show hidden records</param>
        /// <returns>News items</returns>
        public virtual IPagedList<NewsItem> GetAllNews(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<NewsItem>(query, pageIndex, pageSize);
            return news;
        }

        /// <summary>
        /// Inserts a news item
        /// </summary>
        /// <param name="news">News item</param>
        public virtual void InsertNews(NewsItem news)
        {
            if (news == null)
                throw new ArgumentNullException("news");

            _newsItemRepository.Insert(news);

            //event notification
            _eventPublisher.EntityInserted(news);
        }

        /// <summary>
        /// Updates the news item
        /// </summary>
        /// <param name="news">News item</param>
        public virtual void UpdateNews(NewsItem news)
        {
            if (news == null)
                throw new ArgumentNullException("news");

            _newsItemRepository.Update(news);

            //event notification
            _eventPublisher.EntityUpdated(news);
        }

        /// <summary>
        /// Gets news
        /// </summary>
        /// <param name="newsIds">The news identifiers</param>
        /// <returns>News</returns>
        public virtual IList<NewsItem> GetNewsByIds(int[] newsIds)
        {
            var query = _newsItemRepository.Table;
            return query.Where(p => newsIds.Contains(p.Id)).ToList();
        }



        /// <summary>
        /// Gets all comments
        /// </summary>
        /// <param name="customerId">Customer identifier; 0 to load all records</param>
        /// <returns>Comments</returns>
        public virtual IList<NewsComment> GetAllComments(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;
        }

        /// <summary>
        /// Gets a news comment
        /// </summary>
        /// <param name="newsCommentId">News comment identifier</param>
        /// <returns>News comment</returns>
        public virtual NewsComment GetNewsCommentById(int newsCommentId)
        {
            if (newsCommentId == 0)
                return null;

            return _newsCommentRepository.GetById(newsCommentId);
        }

        /// <summary>
        /// Get news comments by identifiers
        /// </summary>
        /// <param name="commentIds">News comment identifiers</param>
        /// <returns>News comments</returns>
        public virtual IList<NewsComment> GetNewsCommentsByIds(int[] commentIds)
        {
            if (commentIds == null || commentIds.Length == 0)
                return new List<NewsComment>();

            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<NewsComment>();
            foreach (int id in commentIds)
            {
                var comment = comments.Find(x => x.Id == id);
                if (comment != null)
                    sortedComments.Add(comment);
            }
            return sortedComments;
        }

        /// <summary>
        /// Deletes a news comments
        /// </summary>
        /// <param name="newsComments">News comments</param>
        public virtual void DeleteNewsComments(IList<NewsComment> newsComments)
        {
            if (newsComments == null)
                throw new ArgumentNullException("newsComments");

            _newsCommentRepository.Delete(newsComments);
        }
        /// <summary>
        /// 更新新闻评论
        /// </summary>
        /// <param name="newsComment"></param>
        public virtual void UpdateNewsComment(NewsComment newsComment)
        {
            if (newsComment == null)
                throw new ArgumentNullException("newsComment");

            _newsCommentRepository.Update(newsComment);
            
            //event notification
            _eventPublisher.EntityUpdated(newsComment);
        }
        /// <summary>
        /// Deletes a news comment
        /// </summary>
        /// <param name="newsComment">News comment</param>
        public virtual void DeleteNewsComment(NewsComment newsComment)
        {
            if (newsComment == null)
                throw new ArgumentNullException("newsComment");

            _newsCommentRepository.Delete(newsComment);
        }
        public virtual IList<NewsItem> GetNewsByCategoryId(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<NewsComment> 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<NewsComment>(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;
        }



        /// <summary>
        /// 搜索所有的新闻
        /// </summary>
        /// <param name="dateFrom"></param>
        /// <param name="dateTo"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="showHidden"></param>
        /// <returns></returns>
        public virtual IPagedList<NewsItem> 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<NewsItem>(query, pageIndex, pageSize);
            return news;
        }


        /// <summary>
        /// 搜索所有的新闻评论
        /// </summary>
        /// <param name="dateFrom"></param>
        /// <param name="dateTo"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="showHidden"></param>
        /// <returns></returns>
        public virtual IPagedList<NewsComment> 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<NewsComment>(query, pageIndex, pageSize);
        }




        #region News pictures

        /// <summary>
        /// Deletes a news picture
        /// </summary>
        /// <param name="newsPicture">News picture</param>
        public virtual void DeleteNewsPicture(NewsPicture newsPicture)
        {
            if (newsPicture == null)
                throw new ArgumentNullException("newsPicture");

            _newsPictureRepository.Delete(newsPicture);

            //event notification
            _eventPublisher.EntityDeleted(newsPicture);
        }

        /// <summary>
        /// Gets a news pictures by newsItem identifier
        /// </summary>
        /// <param name="newsItemId">The news identifier</param>
        /// <returns>News pictures</returns>
        public virtual IList<NewsPicture> GetNewsPicturesByNewsItemId(int newsItemId)
        {
            var query = from np in _newsPictureRepository.Table
                        where np.NewsItemId == newsItemId
                        orderby np.DisplayOrder
                        select np;
            var newsItemPictures = query.ToList();
            return newsItemPictures;
        }

        /// <summary>
        /// Gets a newsItem picture
        /// </summary>
        /// <param name="newsItemIdPictureId">News picture identifier</param>
        /// <returns>News picture</returns>
        public virtual NewsPicture GetNewsPictureById(int newsPictureId)
        {
            if (newsPictureId == 0)
                return null;

            return _newsPictureRepository.GetById(newsPictureId);
        }

        /// <summary>
        /// Inserts a newsItem picture
        /// </summary>
        /// <param name="newsPicture">News picture</param>
        public virtual void InsertNewsPicture(NewsPicture newsPicture)
        {
            if (newsPicture == null)
                throw new ArgumentNullException("newsPicture");

            _newsPictureRepository.Insert(newsPicture);

            //event notification
            _eventPublisher.EntityInserted(newsPicture);
        }

        /// <summary>
        /// Updates a newsItem picture
        /// </summary>
        /// <param name="newsPicture">News picture</param>
        public virtual void UpdateNewsPicture(NewsPicture newsPicture)
        {
            if (newsPicture == null)
                throw new ArgumentNullException("newsPicture");

            _newsPictureRepository.Update(newsPicture);

            //event notification
            _eventPublisher.EntityUpdated(newsPicture);
        }

        /// <summary>
        /// Get the IDs of all newsItem images 
        /// </summary>
        /// <param name="NewsItemIds">News IDs</param>
        /// <returns>All picture identifiers grouped by newsItem ID</returns>
        public IDictionary<int, int[]> GetNewsItemsImagesIds(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
{
    /// <summary>
    /// Repository
    /// </summary>
    public partial interface IRepository<T> where T : BaseEntity
    {
        /// <summary>
        /// Get entity by identifier
        /// </summary>
        /// <param name="id">Identifier</param>
        /// <returns>Entity</returns>
        T GetById(object id);

        /// <summary>
        /// Insert entity
        /// </summary>
        /// <param name="entity">Entity</param>
        void Insert(T entity);

        /// <summary>
        /// Insert entities
        /// </summary>
        /// <param name="entities">Entities</param>
        void Insert(IEnumerable<T> entities);

        /// <summary>
        /// Update entity
        /// </summary>
        /// <param name="entity">Entity</param>
        void Update(T entity);

        /// <summary>
        /// Update entities
        /// </summary>
        /// <param name="entities">Entities</param>
        void Update(IEnumerable<T> entities);

        /// <summary>
        /// Delete entity
        /// </summary>
        /// <param name="entity">Entity</param>
        void Delete(T entity);

        /// <summary>
        /// Delete entities
        /// </summary>
        /// <param name="entities">Entities</param>
        void Delete(IEnumerable<T> entities);

        /// <summary>
        /// Gets a table
        /// </summary>
        IQueryable<T> Table { get; }

        /// <summary>
        /// Gets a table with "no tracking" enabled (EF feature) Use it only when you load record(s) only for read-only operations
        /// </summary>
        IQueryable<T> TableNoTracking { 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<NewsModel>();
        }
        public bool result { get; set; }
        public string msg { get; set; }
        public List<NewsModel> News { get; set; }
    }
    /// <summary>
    /// 新闻
    /// </summary>
    public partial class NewsModel : BaseNopEntityModel
    {
        public NewsModel()
        {
            this.CoverImgUrls = new List<string>();
        }
        /// <summary>
        /// 标题
        /// </summary>
        public string Title { get; set; }
        /// <summary>
        /// 概要
        /// </summary>
        public string Short { get; set; }
        /// <summary>
        /// 详情(新闻列表不传该字段)
        /// </summary>
        public string Full { get; set; }
        /// <summary>
        /// 允许评论
        /// </summary>
        public bool AllowComments { get; set; }
        /// <summary>
        /// 评论量
        /// </summary>
        public int CommentCount { get; set; }
        /// <summary>
        /// 点赞量
        /// </summary>
        public int PrizeCount { get; set; }
        /// <summary>
        /// 创建时间
        /// </summary>
        public string CreatedOn { get; set; }
        /// <summary>
        ///
        /// </summary>
        public bool IsPrize { get; set; }
        /// <summary>
        /// 点击数量
        /// </summary>
        public int ClickCount { get; set; }
        public List<string> CoverImgUrls { get; set; }
    }
}

基本上,还是很清晰的。就跟王者荣耀游戏一样,玩几局,就摸透了。
F12定位恒好用。


本文转自TBHacker博客园博客,原文链接:http://www.cnblogs.com/jiqing9006/p/6868169.html,如需转载请自行联系原作者

相关文章
|
6月前
mvc.net分页查询案例——DLL数据访问层(HouseDLL.cs)
mvc.net分页查询案例——DLL数据访问层(HouseDLL.cs)
|
3月前
|
SQL 开发框架 数据库
".NET开发者的超能力:AgileEAS.NET ORM带你穿越数据库的迷宫,让数据操作变得轻松又神奇!"
【8月更文挑战第16天】AgileEAS.NET是面向.NET平台的企业应用开发框架,核心功能包括数据关系映射(ORM),允许以面向对象方式操作数据库,无需编写复杂SQL。通过继承`AgileEAS.Data.Entity`创建实体类对应数据库表,利用ORM简化数据访问层编码。支持基本的CRUD操作及复杂查询如条件筛选、排序和分页,并可通过导航属性实现多表关联。此外,提供了事务管理功能确保数据一致性。AgileEAS.NET的ORM简化了数据库操作,提升了开发效率和代码可维护性。
51 5
|
24天前
|
SQL XML 关系型数据库
入门指南:利用NHibernate简化.NET应用程序的数据访问
【10月更文挑战第13天】NHibernate是一个面向.NET的开源对象关系映射(ORM)工具,它提供了从数据库表到应用程序中的对象之间的映射。通过使用NHibernate,开发者可以专注于业务逻辑和领域模型的设计,而无需直接编写复杂的SQL语句来处理数据持久化问题。NHibernate支持多种数据库,并且具有高度的灵活性和可扩展性。
39 2
|
3月前
|
开发框架 .NET 数据库连接
闲话 Asp.Net Core 数据校验(三)EF Core 集成 FluentValidation 校验数据例子
闲话 Asp.Net Core 数据校验(三)EF Core 集成 FluentValidation 校验数据例子
|
4月前
|
开发框架 JSON 前端开发
利用查询条件对象,在Asp.net Web API中实现对业务数据的分页查询处理
利用查询条件对象,在Asp.net Web API中实现对业务数据的分页查询处理
|
3月前
|
开发框架 前端开发 算法
分享 .NET EF6 查询并返回树形结构数据的 2 个思路和具体实现方法
分享 .NET EF6 查询并返回树形结构数据的 2 个思路和具体实现方法
|
4月前
|
机器学习/深度学习 计算机视觉 网络架构
【YOLOv8改进 - 注意力机制】HCF-Net 之 PPA:并行化注意力设计 | 小目标
YOLO目标检测专栏介绍了HCF-Net,一种用于红外小目标检测的深度学习模型,它通过PPA、DASI和MDCR模块提升性能。PPA利用多分支特征提取和注意力机制,DASI实现自适应特征融合,MDCR通过多层深度可分离卷积细化空间特征。HCF-Net在SIRST数据集上表现出色,超越其他方法。论文和代码分别在[arxiv.org](https://arxiv.org/pdf/2403.10778)和[github.com/zhengshuchen/HCFNet](https://github.com/zhengshuchen/HCFNet)上。YOLOv8的PPA类展示了整合注意力机制的结构
|
6月前
|
存储 测试技术 计算机视觉
高维数据惩罚回归方法:主成分回归PCR、岭回归、lasso、弹性网络elastic net分析基因数据
高维数据惩罚回归方法:主成分回归PCR、岭回归、lasso、弹性网络elastic net分析基因数据
|
6月前
|
SQL 数据库
使用ADO.NET查询和操作数据
使用ADO.NET查询和操作数据