Generic repository pattern and Unit of work with Entity framework
原文 Generic repository pattern and Unit of work with Entity framework
Repository pattern is an abstraction layer between your business logic layer and data access layer. This abstract layer contains methods to server data from data layer to business layer. Now, changes in your data layer cannot affect the business layer directly.
For more information about repository pattern or unit of work visit this article. Below is my approach how to implement repository pattern and unit of work with entity framework.
1. Create IGenericRepository interface
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
|
public interface IGenericRepository<TEntity> { /// <summary> /// Get all entities from db /// </summary> /// <param name="filter"></param> /// <param name="orderBy"></param> /// <param name="includes"></param> /// <returns></returns> List<TEntity> Get( Expression<Func<TEntity, bool >> filter = null , Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null , params Expression<Func<TEntity, object >>[] includes); /// <summary> /// Get query for entity /// </summary> /// <param name="filter"></param> /// <param name="orderBy"></param> /// <returns></returns> IQueryable<TEntity> Query(Expression<Func<TEntity, bool >> filter = null , Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null ); /// <summary> /// Get single entity by primary key /// </summary> /// <param name="id"></param> /// <returns></returns> TEntity GetById( object id); /// <summary> /// Get first or default entity by filter /// </summary> /// <param name="filter"></param> /// <param name="includes"></param> /// <returns></returns> TEntity GetFirstOrDefault( Expression<Func<TEntity, bool >> filter = null , params Expression<Func<TEntity, object >>[] includes); /// <summary> /// Insert entity to db /// </summary> /// <param name="entity"></param> void Insert(TEntity entity); /// <summary> /// Update entity in db /// </summary> /// <param name="entity"></param> void Update(TEntity entity); /// <summary> /// Delete entity from db by primary key /// </summary> /// <param name="id"></param> void Delete( object id); } |
2. Create GenericRepository class to implement interface
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
|
public class GenericRepository<TEntity> : IGenericRepository<TEntity> where TEntity : class { private DbContext context; private DbSet<TEntity> dbSet; public GenericRepository(DbContext context) { this .context = context; this .dbSet = context.Set<TEntity>(); } public virtual List<TEntity> Get(Expression<Func<TEntity, bool >> filter = null , Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null , params Expression<Func<TEntity, object >>[] includes) { IQueryable<TEntity> query = dbSet; foreach (Expression<Func<TEntity, object >> include in includes) query = query.Include(include); if (filter != null ) query = query.Where(filter); if (orderBy != null ) query = orderBy(query); return query.ToList(); } public virtual IQueryable<TEntity> Query(Expression<Func<TEntity, bool >> filter = null , Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null ) { IQueryable<TEntity> query = dbSet; if (filter != null ) query = query.Where(filter); if (orderBy != null ) query = orderBy(query); return query; } public virtual TEntity GetById( object id) { return dbSet.Find(id); } public virtual TEntity GetFirstOrDefault(Expression<Func<TEntity, bool >> filter = null , params Expression<Func<TEntity, object >>[] includes) { IQueryable<TEntity> query = dbSet; foreach (Expression<Func<TEntity, object >> include in includes) query = query.Include(include); return query.FirstOrDefault(filter); } public virtual void Insert(TEntity entity) { dbSet.Add(entity); } public virtual void Update(TEntity entity) { dbSet.Attach(entity); context.Entry(entity).State = EntityState.Modified; } public virtual void Delete( object id) { TEntity entityToDelete = dbSet.Find(id); if (context.Entry(entityToDelete).State == EntityState.Detached) { dbSet.Attach(entityToDelete); } dbSet.Remove(entityToDelete); } } |
3. Create IUnitOfWork interface
1
2
3
4
5
|
public interface IUnitOfWork { IGenericRepository<Model> ModelRepository { get ; } void Save(); } |
4. Create UnitOfWork class to implement interface
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
public class UnitOfWork : IUnitOfWork, System.IDisposable { private readonly MyDatabaseContext _context; private IGenericRepository<Model> _modelRepository; public UnitOfWork(MyDatabaseContext context) { _context = context; } public IGenericRepository<Model> ModelRepository { get { return _modelRepository ?? (_modelRepository = new GenericRepository<Model>(_context)); } } public void Save() { _context.SaveChanges(); } private bool disposed = false ; protected virtual void Dispose( bool disposing) { if (! this .disposed) { if (disposing) { _context.Dispose(); } } this .disposed = true ; } public void Dispose() { Dispose( true ); System.GC.SuppressFinalize( this ); } } |
5. Usage in controller
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
public class HomeController : Controller { private IUnitOfWork _unitOfWork; public HomeController(IUnitOfWork unitOfWork) { _unitOfWork = unitOfWork; } // // GET: /Home/ public ActionResult Index() { // get all models (all properties) List<Model> modelList = _unitOfWork.ModelRepository.Get(m => m.FirstName == "Jan" || m.LastName == "Holinka" , includeProperties: "Account" ); // get all models (some properties) List<ModelDto> modelDtoList = _unitOfWork.UserRepository .Query(x => x.FirstName == "Jan" || x.LastName == "Holinka" ) .Select(x => new ModelDto { FirstName = x.FirstName, LastName = x.LastName }) .ToList(); return View( "Index" ); } // show list of models in view return View(modelList); } } public class ModelDto { public string FirstName { get ; set ; } public string LastName { get ; set ; } } |
That's all.
Generic repository pattern and Unit of work with Entity framework的更多相关文章
- Using the Repository Pattern with ASP.NET MVC and Entity Framework
原文:http://www.codeguru.com/csharp/.net/net_asp/mvc/using-the-repository-pattern-with-asp.net-mvc-and ...
- [转]Using the Repository Pattern with ASP.NET MVC and Entity Framework
本文转自:http://www.codeguru.com/csharp/.net/net_asp/mvc/using-the-repository-pattern-with-asp.net-mvc-a ...
- Follow me to learn what is repository pattern
Introduction Creating a generic repository pattern in an mvc application with entity framework is th ...
- [转]Upgrading to Async with Entity Framework, MVC, OData AsyncEntitySetController, Kendo UI, Glimpse & Generic Unit of Work Repository Framework v2.0
本文转自:http://www.tuicool.com/articles/BBVr6z Thanks to everyone for allowing us to give back to the . ...
- Asp.net webform scaffolding结合Generic Unit of Work & (Extensible) Repositories Framework代码生成向导
Asp.net webform scaffolding结合Generic Unit of Work & (Extensible) Repositories Framework代码生成向导 在上 ...
- Using Repository Pattern in Entity Framework
One of the most common pattern is followed in the world of Entity Framework is “Repository Pattern”. ...
- Laravel与Repository Pattern(仓库模式)
为什么要学习Repository Pattern(仓库模式) Repository 模式主要思想是建立一个数据操作代理层,把controller里的数据操作剥离出来,这样做有几个好处: 把数据处理逻辑 ...
- 在Entity Framework 4.0中使用 Repository 和 Unit of Work 模式
[原文地址]Using Repository and Unit of Work patterns with Entity Framework 4.0 [原文发表日期] 16 June 09 04:08 ...
- Using StructureMap DI and Generic Repository
In this post, i will show how to use generic repository and dependency injection using structuremap. ...
随机推荐
- VB最新使用教程
Visual Basic是一种由 微软公司开发的结构化的.模块化的.面向对象的.包含协助开发环境的事件驱动为机制的可视化程序设计语言.这是一种可用于微软自家产品开发的语言.它源自于BASIC编程语言. ...
- itertools模块速查
学习itertools模块记住这张表就OK了 参考:http://docs.python.org/2/library/itertools.html#module-itertools Infinite ...
- 全民wifi钓鱼来临----agnes安卓wifi钓鱼神器介绍
断断续续搞了一些无线的东西,从bt5的aircrack-ng的破无线(没怎么成功过)其实EWSA这个用GPU跑还算不错,可惜了我这显卡也只能每秒2500,到用c118在OsmocomBB基础上进行gs ...
- js原型链与继承(初体验)
js原型链与继承是js中的重点,所以我们通过以下三个例子来进行详细的讲解. 首先定义一个对象obj,该对象的原型为obj._proto_,我们可以用ES5中的getPrototypeOf这一方法来查询 ...
- cadence 16.6 Pspice 仿真步骤
从ADI官网下载后缀为 cir 的文件,AD8210 为例 进行仿真 1 打开 Cadence -> Release 16.6 -> PSpice Accessories -> Mo ...
- 用于主题检测的临时日志(d94169f9-f1c0-45a2-82d4-6edc4bd35539 - 3bfe001a-32de-4114-a6b4-4005b770f6d7)
这是一个未删除的临时日志.请手动删除它.(5327dce0-d2d1-4fba-8801-d3ff67564a96 - 3bfe001a-32de-4114-a6b4-4005b770f6d7)
- auto和decltype
auto 1.编译器通过分析表达式的类型来确定变量的类型,所以auto定义的变量必须有初始值. auto i=; //ok,i为整型 auto j; //error,定义时必须初始化. j=; ...
- ruby condition
class.new 新建class.find 查询class.destroy 删除 变量查询a="hahaha"Product.find(:all,:conditions=> ...
- Jenkins部署.NET网站项目
Jenkins Jenkins是一个开源软件项目,旨在提供一个开放易用的软件平台,使软件的持续集成变成可能. Jenkins是基于Java开发的一种持续集成工具,用于监控持续重复的工作,功能包括: 持 ...
- 不用安装语言包,教你将PS界面语言修改成默认语言(英语)
地址:http://www.cnblogs.com/Loonger/p/5112020.html 嗯,干脆利落,直接上教程.超简单的方法.(该方法可以随时在你已有语言[非英语]和PS默认语言[英语]之 ...