惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

P
Privacy International News Feed
WordPress大学
WordPress大学
Security Latest
Security Latest
Cyberwarzone
Cyberwarzone
K
Kaspersky official blog
Cisco Talos Blog
Cisco Talos Blog
Microsoft Security Blog
Microsoft Security Blog
G
GRAHAM CLULEY
N
News | PayPal Newsroom
Apple Machine Learning Research
Apple Machine Learning Research
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
V
Visual Studio Blog
美团技术团队
J
Java Code Geeks
I
Intezer
The Cloudflare Blog
SecWiki News
SecWiki News
S
Secure Thoughts
Microsoft Azure Blog
Microsoft Azure Blog
V2EX - 技术
V2EX - 技术
C
Cyber Attacks, Cyber Crime and Cyber Security
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Spread Privacy
Spread Privacy
D
DataBreaches.Net
S
Security Affairs
Help Net Security
Help Net Security
S
Securelist
F
Full Disclosure
C
Check Point Blog
F
Fortinet All Blogs
Know Your Adversary
Know Your Adversary
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Y
Y Combinator Blog
云风的 BLOG
云风的 BLOG
阮一峰的网络日志
阮一峰的网络日志
The Register - Security
The Register - Security
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
人人都是产品经理
人人都是产品经理
博客园_首页
G
Google Developers Blog
Google Online Security Blog
Google Online Security Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
H
Help Net Security
酷 壳 – CoolShell
酷 壳 – CoolShell
I
InfoQ
Application and Cybersecurity Blog
Application and Cybersecurity Blog
H
Hacker News: Front Page
L
LINUX DO - 热门话题
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
L
LangChain Blog

博客园 - JIN Weijie

基于Dapper的分页实现,支持筛选,排序,结果集总数,多表查询,非存储过程 让Windows 7变成WIFI热点 新浪微博RSS生成器Ver 1.0 同步Twitter帐号 修改Thickbox,预加载图片和点击图片前后浏览 ASTreeView 1.5.8发布(ASP.Net树控件) ASTreeView 1.5.3发布(ASP.NET树控件) ASTreeView 1.4.0发布(ASP.NET树控件) ASTreeView 1.3.0发布(ASP.NET树控件) ASTreeView 1.1.1发布(ASP.NET树控件) 在GoDaddy上部署SubText ASTreeView 1.0发布(一个ASP.NET树控件) 自定义增加Windows xp IIS的连接数 javascript closure(闭包)的一个示例 vmware增加磁盘空间方法以及出错解决 <=本博客已经转移至jinweijie.com=> [js][asp.net]客户端控制validator [asp.net]优化ViewState [js]remove whitespace for firefox [windows]自动拨号脚本
基于Entity Framework的自定义分页,增删改的通用实现
JIN Weijie · 2017-07-24 · via 博客园 - JIN Weijie

简介

之前写个一个基于Dapper的分页实现,现在再来写一个基于Entity Framework的分页实现,以及增删改的通用实现。

代码

还是先上代码:https://github.com/jinweijie/EF.GenericRepository

如何运行示例

还是像先前一样:

1. 先Clone下代码,在Database里面解压缩Database.7z

2. Attach到Sql Server LocalDB上。如果你用的不是Sql Server的LocalDB,你需要更改App.Config里的连接字符串。

3. Ctrl + F5,运行示例程序。

Repository 基类 - 查询

Common\AbstractRepository.cs 是Repository的基类,实现了增删改查的一些方法,例如:

public virtual Tuple<IEnumerable<T>, int> Find(Expression<Func<T, bool>> criteria
            , int pageIndex
            , int pageSize
            , string[] asc
            , string[] desc
            , params Expression<Func<T, object>>[] includeProperties)

这个方法是AbstractRepository查询方法中的一个,用于自定义分页查询,其中criteria 为一个表达式,作为查询的条件,参数pageIndex, pageSize, asc, desc为分页相关参数;

关于多表(关联表):

includeProperties为在多表时候,Join相关联的表。因为EF默认是Lazy Loading,相关联的表默认不是立即加载的,所以有时候如果写代码不小心,在for循环里就有可能会循环查询n个字表。用来includeProperties参数,就可以在查询时候join关联表。

Repository 基类 - 增删改

AbstractRepository已经用泛型实现了增删改方法:

  • public virtual T Create(T entity)
  • public virtual T Update(T entity)
  • public virtual T CreateOrUpdate(T entity)
  • public virtual void Delete(TId id)

 另外,关于transaction的实现,我使用了Unit of Work模式,多个Repository共享一个DBContext,关于UOW,请在Common\UnitOfWork.cs里找到。

 调用UOW的时候,基本类似于这样:

var uow = new EFUnitOfWork();
var repo = uow.GetLogRepository();

repo.Create(new Log
{
    LevelId = 1,
    Thread = "",
    Location = "Manual Creation",
    Message = "This is manually created log.",
    CreateTime = DateTimeOffset.Now,
    Date = DateTime.Now
});

uow.Commit();

从UnitOfWork里得到一个或多个Repository,共享DBContext,做增删改操作,最后uow统一SaveChanges。

 Repository的派生类

由于已经有了AbstractRepository,实现了增删改查的很多方法,所以派生类,例如示例项目里的LogRepository基本就可以变得很简单,主要实现一些特定的业务逻辑,在示例项目里,因为没有特殊的业务逻辑,所以会很简单:

    public class LogRepository : AbstractRepository<Log, int>
    {
        public LogRepository(EFContext context)
            : base(context)
        {
        }
    }

关于Entity的生成

本人比较喜欢Database First 实现,先设计数据库,然后用edmx reverse engineering,生成POCO。可以参考Entity目录下的相关文件。

当然,如果你喜欢Code First,同样没有问题,仍然适用本文的实现。

使用Logging日志追踪EF SQL

在使用Entity Framework的时候,最好关心一下EF所生成的SQL,这样可以在开发阶段发现一些潜在的性能问题,避免在生产环境焦头烂额:)

在Common\EFContext.cs 里,有一个配置项EnableTraceSql,如果为true,那么所以EF生成的SQL将会被nlog记录下来。我将nlog的日志配置到了数据库。也就是说,在你运行示例项目时,每次查询,都会增加新的日志记录,内容为查询时生成的SQL:

 Specification Pattern

在查询方法里,有个重载是接受一个ISpecification示例,这样的实现可以有效的控制业务逻辑,对于写给被其他人调用的接口来说,可以明确的确定查询参数,例如:

    public class LogSearchSpecification : ISpecification<Log>
    {
        public string LevelName { get; set; }
        public string Message { get; set; }
        public Expression<Func<Log, bool>> ToExpression()
        {
            return log => (log.Level.Name == LevelName || LevelName == "") &&
                          (log.Message.Contains(Message) || Message == "");
        }

        public bool IsSatisfiedBy(Log entity)
        {
            return (entity.Level.Name == LevelName || LevelName == "") &&
                   (entity.Message.Contains(Message) || Message == "");
        }
    }

那么,调用这个查询方法的代码就可以明确知道,我的查询条件为LevelName和Message,至于LevelName是等于以及Message为Like则是在LogSearchSpeficiation里实现,做到很好的封装。

最后

这套实现是几年来平时慢慢积累的,是经过实践的,所以应该可以作为一定的参考,当然,在具体的项目里,可以用一些DI去拿到Repository等等,不在本文讨论范围,大家可以自由发挥,希望对大家可以有所帮助,谢谢。