分享基于EF6、Unitwork、Autofac的Repository模式设计
分享基于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模式设计的更多相关文章
- 分享基于Entity Framework的Repository模式设计(附源码)
关于Repository模式,在这篇文章中有介绍,Entity Framework返回IEnumerable还是IQueryable? 这篇文章介绍的是使用Entity Framework实现的Rep ...
- 项目开发中的一些注意事项以及技巧总结 基于Repository模式设计项目架构—你可以参考的项目架构设计 Asp.Net Core中使用RSA加密 EF Core中的多对多映射如何实现? asp.net core下的如何给网站做安全设置 获取服务端https证书 Js异常捕获
项目开发中的一些注意事项以及技巧总结 1.jquery采用ajax向后端请求时,MVC框架并不能返回View的数据,也就是一般我们使用View().PartialView()等,只能返回json以 ...
- 基于Repository模式设计项目架构—你可以参考的项目架构设计
关于Repository模式,直接百度查就可以了,其来源是<企业应用架构模式>.我们新建一个Infrastructure文件夹,这里就是基础设施部分,EF Core的上下文类以及Repos ...
- Repository模式介绍汇总
1.Linq To Sql中Repository模式应用场景 http://www.cnblogs.com/zhijianliutang/archive/2012/02/24/2367305.html ...
- LCLFramework框架之Repository模式
Respository模式在示例中的实际目的小结一下 Repository模式是架构模式,在设计架构时,才有参考价值: Repository模式主要是封装数据查询和存储逻辑: Repository模式 ...
- 基于ASP.NET WPF技术及MVP模式实战太平人寿客户管理项目开发(Repository模式)
亲爱的网友,我这里有套课程想和大家分享,假设对这个课程有兴趣的.能够加我的QQ2059055336和我联系. 课程背景 本课程是教授使用WPF.ADO.NET.MVVM技术来实现太平人寿保险有限公司 ...
- 使用ASP.NET Web Api构建基于REST风格的服务实战系列教程【二】——使用Repository模式构建数据库访问层
系列导航地址http://www.cnblogs.com/fzrain/p/3490137.html 前言 在数据访问层应用Repository模式来隔离对领域对象的细节操作是很有意义的.它位于映射层 ...
- 基于EF Core的Code First模式的DotNetCore快速开发框架
前言 最近接了几个小单子,因为是小单子,项目规模都比较小,业务相对来说,也比较简单.所以在选择架构的时候,考虑到效率方面的因素,就采取了asp.net+entity framework中的code f ...
- 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,这种形 ...
随机推荐
- transform 遇上 position: fixed
最近遇到一个有意思的现象,以下 demo 中 fixed 的元素没有相对 viewport 定位,而是相对于它的父元素进行定位. <html> <head> <style ...
- ArcGIS for Desktop入门教程_第七章_使用ArcGIS进行空间分析 - ArcGIS知乎-新一代ArcGIS问答社区
原文:ArcGIS for Desktop入门教程_第七章_使用ArcGIS进行空间分析 - ArcGIS知乎-新一代ArcGIS问答社区 1 使用ArcGIS进行空间分析 1.1 GIS分析基础 G ...
- 微信小程序把玩(三十三)Record API
原文:微信小程序把玩(三十三)Record API 其实这个API也挺奇葩的,录音结束后success不走,complete不走,fail也不走, 不知道是不是因为电脑测试的原因,只能等公测或者等他们 ...
- 微信小程序把玩(十九)radio组件
原文:微信小程序把玩(十九)radio组件 radio组件为单选组件与radio-group组合使用,使用方式和checkbox没啥区别 主要属性: wxml <!--设置监听器,当点击radi ...
- 专访Rust——由Mozilla开发的系统编程语言(目标人群就是那些纠结的C++程序员,甚至也是他们自己)
Rust是由Mozilla开发的专门用来编写高性能应用程序的系统编程语言.以下是对Rust的创始人——Graydon Hoare的采访. Graydon Hoare,自称为职业编程语言工程师,从200 ...
- hadoop 数据抽取
#!/bin/bash if [ ! -z $2 ]; then start_time=$1 end_time=$2 else starttime=`date +%Y%m%d%H%M -d '-15 ...
- Python连载12-shutil模块
一.shutil模块 1.函数:copy() (1)用法:复制文件0 (2)格式:copy(来源路径,目标路径) (3)返回值:返回目标路径 (4)注意:拷贝的同时可以给文件重命名 source_pa ...
- 30212Java_数组
数组 1.综述 数组是相同类型数据的有序集合.数组描述的是相同类型的若干个数据,按照一定的先后次序排列组合而成. 其中,每一个数据称作一个元素,每个元素可以通过一个索引(下标)来访问它们. 数组的三个 ...
- 626. Exchange Seats-(LeetCode之Database篇)
问题表述 数据库表如下: id student 1 Abbot 2 Doris 3 Emerson 4 Green 5 Jeames 现在要通过SQL语句将表变换成如下: id student 1 D ...
- 一文详解 LVS、Nginx 及 HAProxy 工作原理( 附大图 )
当前大多数的互联网系统都使用了服务器集群技术,集群是将相同服务部署在多台服务器上构成一个集群整体对外提供服务,这些集群可以是 Web 应用服务器集群,也可以是数据库服务器集群,还可以是分布式缓存服务器 ...