分享基于EF6、Unitwork、Autofac的Repository模式设计

一、实现的思路和结构图

  • Repository的共同性

有一些公共的方法(增删改查), 这些方法无关于Repository操作的是哪个实体类,可以把这些方法定义成接口IRepository,然后有个基类BaseRepository实现该接口的方法。常见的方法,比如Find, Filter, Delete, Create等

  • Repository的差异性

每个Repository类又会有一些差异性,应当允许它们能够继承BaseRepository之外,还能够再扩展自己的一些方法。所以每个类都可以再定义一个自己特有的接口,定义一些属于自己Repository的方法。

  • Repository的协同性

不同的Repository可能需要协同,Repository对数据的修改,需要在统一的保存.

最终实现的类结构图如下:

二、Repository设计具体的实现代码

IRepository接口定义了Repository共有的方法, BaseRepository实现了这些接口的方法。其它的Repository类再集成BaseRepository方法,就天然的得到了对数据操作的基本方法。

  • IRepository代码
    public interface IRepository<TEntity> where TEntity : class
{
/// <summary>
/// Gets all objects from database
/// </summary>
/// <returns></returns>
IQueryable<TEntity> All(); /// <summary>
/// Gets objects from database by filter.
/// </summary>
/// <param name="predicate">Specified a filter</param>
/// <returns></returns>
IQueryable<TEntity> Filter(Expression<Func<TEntity, bool>> predicate); /// <summary>
/// Gets objects from database with filtering and paging.
/// </summary>
/// <param name="filter">Specified a filter</param>
/// <param name="total">Returns the total records count of the filter.</param>
/// <param name="index">Specified the page index.</param>
/// <param name="size">Specified the page size</param>
/// <returns></returns>
IQueryable<TEntity> Filter(Expression<Func<TEntity, bool>> filter, out int total, int index = 0, int size = 50); /// <summary>
/// Gets the object(s) is exists in database by specified filter.
/// </summary>
/// <param name="predicate">Specified the filter expression</param>
/// <returns></returns>
bool Contains(Expression<Func<TEntity, bool>> predicate); /// <summary>
/// Find object by keys.
/// </summary>
/// <param name="keys">Specified the search keys.</param>
/// <returns></returns>
TEntity Find(params object[] keys); /// <summary>
/// Find object by specified expression.
/// </summary>
/// <param name="predicate"></param>
/// <returns></returns>
TEntity Find(Expression<Func<TEntity, bool>> predicate); /// <summary>
/// Create a new object to database.
/// </summary>
/// <param name="t">Specified a new object to create.</param>
/// <returns></returns>
void Create(TEntity t); /// <summary>
/// Delete the object from database.
/// </summary>
/// <param name="t">Specified a existing object to delete.</param>
void Delete(TEntity t); /// <summary>
/// Delete objects from database by specified filter expression.
/// </summary>
/// <param name="predicate"></param>
/// <returns></returns>
int Delete(Expression<Func<TEntity, bool>> predicate); /// <summary>
/// Update object changes and save to database.
/// </summary>
/// <param name="t">Specified the object to save.</param>
/// <returns></returns>
void Update(TEntity t); /// <summary>
/// Select Single Item by specified expression.
/// </summary>
/// <param name="expression"></param>
/// <returns></returns>
TEntity FirstOrDefault(Expression<Func<TEntity, bool>> expression);
}
  • BaseRepository代码
    public class BaseRepository<TEntity> : IRepository<TEntity> where TEntity : class
{
protected readonly DbContext Context; public BaseRepository(DbContext context)
{
Context = context;
} /// <summary>
/// Gets all objects from database
/// </summary>
/// <returns></returns>
public IQueryable<TEntity> All()
{
return Context.Set<TEntity>().AsQueryable();
} /// <summary>
/// Gets objects from database by filter.
/// </summary>
/// <param name="predicate">Specified a filter</param>
/// <returns></returns>
public virtual IQueryable<TEntity> Filter(Expression<Func<TEntity, bool>> predicate)
{
return Context.Set<TEntity>().Where<TEntity>(predicate).AsQueryable<TEntity>();
} /// <summary>
/// Gets objects from database with filtering and paging.
/// </summary>
/// <param name="filter">Specified a filter</param>
/// <param name="total">Returns the total records count of the filter.</param>
/// <param name="index">Specified the page index.</param>
/// <param name="size">Specified the page size</param>
/// <returns></returns>
public virtual IQueryable<TEntity> Filter(Expression<Func<TEntity, bool>> filter, out int total, int index = 0,
int size = 50)
{
var skipCount = index * size;
var resetSet = filter != null
? Context.Set<TEntity>().Where<TEntity>(filter).AsQueryable()
: Context.Set<TEntity>().AsQueryable();
resetSet = skipCount == 0 ? resetSet.Take(size) : resetSet.Skip(skipCount).Take(size);
total = resetSet.Count();
return resetSet.AsQueryable();
} /// <summary>
/// Gets the object(s) is exists in database by specified filter.
/// </summary>
/// <param name="predicate">Specified the filter expression</param>
/// <returns></returns>
public bool Contains(Expression<Func<TEntity, bool>> predicate)
{
return Context.Set<TEntity>().Any(predicate);
} /// <summary>
/// Find object by keys.
/// </summary>
/// <param name="keys">Specified the search keys.</param>
/// <returns></returns>
public virtual TEntity Find(params object[] keys)
{
return Context.Set<TEntity>().Find(keys);
} /// <summary>
/// Find object by specified expression.
/// </summary>
/// <param name="predicate"></param>
/// <returns></returns>
public virtual TEntity Find(Expression<Func<TEntity, bool>> predicate)
{
return Context.Set<TEntity>().FirstOrDefault<TEntity>(predicate);
} /// <summary>
/// Create a new object to database.
/// </summary>
/// <param name="t">Specified a new object to create.</param>
/// <returns></returns>
public virtual void Create(TEntity t)
{
Context.Set<TEntity>().Add(t);
} /// <summary>
/// Delete the object from database.
/// </summary>
/// <param name="t">Specified a existing object to delete.</param>
public virtual void Delete(TEntity t)
{
Context.Set<TEntity>().Remove(t);
} /// <summary>
/// Delete objects from database by specified filter expression.
/// </summary>
/// <param name="predicate"></param>
/// <returns></returns>
public virtual int Delete(Expression<Func<TEntity, bool>> predicate)
{
var objects = Filter(predicate);
foreach (var obj in objects)
Context.Set<TEntity>().Remove(obj);
return Context.SaveChanges();
} /// <summary>
/// Update object changes and save to database.
/// </summary>
/// <param name="t">Specified the object to save.</param>
/// <returns></returns>
public virtual void Update(TEntity t)
{
try
{
var entry = Context.Entry(t);
Context.Set<TEntity>().Attach(t);
entry.State = EntityState.Modified;
}
catch (OptimisticConcurrencyException ex)
{
throw ex;
}
} /// <summary>
/// Select Single Item by specified expression.
/// </summary>
/// <param name="expression"></param>
/// <returns></returns>
public TEntity FirstOrDefault(Expression<Func<TEntity, bool>> expression)
{
return All().FirstOrDefault(expression);
}
}

IUnitOfWork接口定义了方法获取特定的Repository, 执行存储过程, SaveChange方法提交修改,统一更新数据。

  • IUnitOfWork接口代码:
    public interface IUnitOfWork : IDisposable
{
DbContext DbContext { get; }
TRepository GetRepository<TRepository>() where TRepository : class;
void ExecuteProcedure(string procedureCommand, params object[] sqlParams);
void ExecuteSql(string sql);
List<T> SqlQuery<T>(string sql);
void SaveChanges();
}

UnitOfWork代码, 代码中使用到了Autofac中的IComponentContext来获取Repository实例

    public class UnitOfWork : IUnitOfWork
{
private readonly IComponentContext _componentContext;
protected readonly DbContext Context; public UnitOfWork(DbContext context, IComponentContext componentContext)
{
Context = context;
_componentContext = componentContext;
} public DbContext DbContext => Context; public TRepository GetRepository<TRepository>() where TRepository : class
{
return _componentContext.Resolve<TRepository>();
} public void ExecuteProcedure(string procedureCommand, params object[] sqlParams)
{
Context.Database.ExecuteSqlCommand(procedureCommand, sqlParams);
} public void ExecuteSql(string sql)
{
Context.Database.ExecuteSqlCommand(sql);
} public List<T> SqlQuery<T>(string sql)
{
return Context.Database.SqlQuery<T>(sql).ToList();
} public void SaveChanges()
{
try
{
Context.SaveChanges();
}
catch (InvalidOperationException ex)
{
if (!ex.Message.Contains("The changes to the database were committed successfully"))
{
throw;
}
}
} public void Dispose()
{
Context?.Dispose();
}
}

三、Repository设计的具体的使用

这里我们定义一个IStudentRepository接口, 包含了方法GetAllStudents(), 同时继承于IRepository<Student>接口

public interface IStudentRepository : IRepository<Student>
{
IEnumerable<dynamic> GetAllStudents();
}

接着定义StudentRepository类来实现这个接口

public class StudentRepository : BaseRepository<Student>, IStudentRepository
{
private readonly SchoolContext _context; public StudentRepository(SchoolContext context)
: base(context)
{
_context = context;
} public IEnumerable<dynamic> GetAllStudents()
{
return _context.Students;
}
}
  • Application_Start方法中使用Autofac注册Repository的代码如下:
    var builder = new ContainerBuilder();

    //register controllers
builder.RegisterControllers(typeof(MvcApplication).Assembly); //register repository
builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).AsImplementedInterfaces(); //add the Entity Framework context to make sure only one context per request
builder.RegisterType<SchoolContext>().InstancePerRequest();
builder.Register(c => c.Resolve<SchoolContext>()).As<DbContext>().InstancePerRequest(); var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
  • 在控制器中注入使用Repository的代码如下:
private readonly IUnitOfWork _repositoryCenter;

private readonly IStudentRepository _studentRepository;

public HomeController(IUnitOfWork repositoryCenter)
{
_repositoryCenter = repositoryCenter;
_studentRepository = _repositoryCenter.GetRepository<IStudentRepository>();
} public ActionResult Index(Student sessionStudent)
{
var students = _studentRepository.GetAllStudents(); // 同时你也可以使用定义于IRepository<Student>中的方法, 比如: _studentRepository.Delete(students.First());
_repositoryCenter.SaveChanges(); ... return View(students);
}

四、思路总结

上面的设计,把Repository的通用代码剥离到父类中,同时又允许每个Repository扩展自己的方法,达到了比较理想的状态。

只是现在的设计和Autofac耦合了,但是如果想继续剥离Autofac直接使用 _repositoryCenter.GetRepository<IStudentRepository>(); 的方式获取IStudentRepository的实例就很困难了。

五、案例源码

源代码仓库 AutoFacMvc

分享基于EF6、Unitwork、Autofac的Repository模式设计的更多相关文章

  1. 分享基于Entity Framework的Repository模式设计(附源码)

    关于Repository模式,在这篇文章中有介绍,Entity Framework返回IEnumerable还是IQueryable? 这篇文章介绍的是使用Entity Framework实现的Rep ...

  2. 项目开发中的一些注意事项以及技巧总结 基于Repository模式设计项目架构—你可以参考的项目架构设计 Asp.Net Core中使用RSA加密 EF Core中的多对多映射如何实现? asp.net core下的如何给网站做安全设置 获取服务端https证书 Js异常捕获

    项目开发中的一些注意事项以及技巧总结   1.jquery采用ajax向后端请求时,MVC框架并不能返回View的数据,也就是一般我们使用View().PartialView()等,只能返回json以 ...

  3. 基于Repository模式设计项目架构—你可以参考的项目架构设计

    关于Repository模式,直接百度查就可以了,其来源是<企业应用架构模式>.我们新建一个Infrastructure文件夹,这里就是基础设施部分,EF Core的上下文类以及Repos ...

  4. Repository模式介绍汇总

    1.Linq To Sql中Repository模式应用场景 http://www.cnblogs.com/zhijianliutang/archive/2012/02/24/2367305.html ...

  5. LCLFramework框架之Repository模式

    Respository模式在示例中的实际目的小结一下 Repository模式是架构模式,在设计架构时,才有参考价值: Repository模式主要是封装数据查询和存储逻辑: Repository模式 ...

  6. 基于ASP.NET WPF技术及MVP模式实战太平人寿客户管理项目开发(Repository模式)

    亲爱的网友,我这里有套课程想和大家分享,假设对这个课程有兴趣的.能够加我的QQ2059055336和我联系.  课程背景 本课程是教授使用WPF.ADO.NET.MVVM技术来实现太平人寿保险有限公司 ...

  7. 使用ASP.NET Web Api构建基于REST风格的服务实战系列教程【二】——使用Repository模式构建数据库访问层

    系列导航地址http://www.cnblogs.com/fzrain/p/3490137.html 前言 在数据访问层应用Repository模式来隔离对领域对象的细节操作是很有意义的.它位于映射层 ...

  8. 基于EF Core的Code First模式的DotNetCore快速开发框架

    前言 最近接了几个小单子,因为是小单子,项目规模都比较小,业务相对来说,也比较简单.所以在选择架构的时候,考虑到效率方面的因素,就采取了asp.net+entity framework中的code f ...

  9. C# 嵌入dll 动软代码生成器基础使用 系统缓存全解析 .NET开发中的事务处理大比拼 C#之数据类型学习 【基于EF Core的Code First模式的DotNetCore快速开发框架】完成对DB First代码生成的支持 基于EF Core的Code First模式的DotNetCore快速开发框架 【懒人有道】在asp.net core中实现程序集注入

    C# 嵌入dll   在很多时候我们在生成C#exe文件时,如果在工程里调用了dll文件时,那么如果不加以处理的话在生成的exe文件运行时需要连同这个dll一起转移,相比于一个单独干净的exe,这种形 ...

随机推荐

  1. WinForm 清空界面控件值的小技巧

    原文:WinForm 清空界面控件值的小技巧 在WinForm里面有时候需要清空自己输入内容或是选择的选项,以便重新操作流程,那么一般你是怎么清空界面各个控件值的呢?如果窗体里面控件,尤其是TextB ...

  2. C# Excel导入Access

    /// <summary> /// 导入 /// </summary> private void btn_In_Click(object sender, EventArgs e ...

  3. C# mysql set和enum属性字段的读取和添加

    1.使用Navicat for Mysql设置set和enum属性字段: a.enum类型 b.set类型 enum类型在创建表时需要设置初始值,在如图所示的位置设置. 2.C#读取和添加数据 a.e ...

  4. 毕设(二)C#SerialPort

    毕业设计中,用到串口与无人机通信,所以就用到了SerialPort这个类,这个类在设置属性时, 用到最主要的属性应该是COM口和波特率,由于本人不熟悉硬件,不便多说,但经验告诉我是这样的, 还有数据位 ...

  5. uniDAC使用sqlite3作为 IOS APP 的数据库存在的问题

    前面有写,可以利用uniConnection的ForceCreateDatabase参数,强制建立sqlite本地数据库, uniConnection1.SpecificOptions.Values[ ...

  6. PHP开发框架 Laravel

    Laravel 是一套简洁.优雅的PHP Web开发框架(PHP Web Framework).它可以让你从面条一样杂乱的代码中解脱出来:它可以帮你构建一个完美的网络APP,而且每行代码都可以简洁.富 ...

  7. coci2018 题解

    plahte 给定一些矩形和一些有颜色的点,求每个矩形上有多少种颜色的点,保证矩形只有包含和不相交两种关系,规模 \(10^5\). 把每个矩形看成一个点,用扫描线建出森林,同时也顺便处理点. 然后做 ...

  8. C++虚函数表解析(图文并茂,非常清楚)( 任何妄图使用父类指针想调用子类中的未覆盖父类的成员函数的行为都会被编译器视为非法)good

    C++中的虚函数的作用主要是实现了多态的机制.关于多态,简而言之就是用父类型别的指针指向其子类的实例,然后通过父类的指针调用实际子类的成员函数.这种技术可以让父类的指针有“多种形态”,这是一种泛型技术 ...

  9. OSGEarth环境搭建

    1.下载OsgEaarth2.8源码 https://codeload.github.com/gwaldron/osgearth/legacy.zip/osgearth-2.8 2.下载perl 编译 ...

  10. Qemu搭建ARM vexpress开发环境(三)----NFS网络根文件系统

    Qemu搭建ARM vexpress开发环境(三)----NFS网络根文件系统 标签(空格分隔): Qemu ARM Linux 经过上一篇<Qemu搭建ARM vexpress开发环境(二)- ...