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. ...
随机推荐
- mslookup
Microsoft Windows [版本 6.1.7601]版权所有 (c) 2009 Microsoft Corporation.保留所有权利. C:\Users\Administrator> ...
- pyQuery的安装
1. 直接通过pip安装 你会发现lxml怎么搞都报错,后来单独先安装libxml2和libxslt pip是找不到这个包的,只好百度.发现有很多的例子的解决方案.后来发现了个实用的. 2. 先安装l ...
- openerp模块收藏 移除下拉选择列表中的“创建并编辑”链接(转载)
移除下拉选择列表中的“创建并编辑”链接 原文:http://shine-it.net/index.php/topic,5990.0.html 有时希望下拉列表中列出的项是与主表某个字段关联的,用户只能 ...
- objdump的使用方法和 symbol table的每列的含义
一.objdump的用法 objdump命令的man手册 objdump [-a] [-b bfname| --target=bfdname] [-C] [--debugging] ...
- 银行HR:寒门再难出贵子
银行HR:寒门再难出贵子来源:金融行业网 2013 年 8 月 6 日 来源:天涯社区 作者:永乐大帝二世 本文是一位银行的HR写的,他工作了10年,接待了一群到银行实习的实习生,然后观察他们发生的好 ...
- gtest功能测试一
一.前言 这篇文章主要总结gtest中的所有断言相关的宏. gtest中,断言的宏可以理解为分为两类,一类是ASSERT系列,一类是EXPECT系列.一个直观的解释就是: 1. ASSERT_* 系列 ...
- EF中使用Select new 方法中字段值替换的问题
前提需要替换查询得到的List当中的某个字段的值,替换规则有一个mapping关系 尝试代码 有问题 无法获取任何数据 /// <summary> /// 获取Treegrid的List ...
- 【h5-egret】如何快速开发一个小游戏
1.环境搭建 安装教程传送门:http://edn.egret.com/cn/index.php?g=&m=article&a=index&id=207&terms1_ ...
- SNV ConnerStore使用说明
1. 上传自己新建的文件新建的类文件 后面的 会有A标示要先 Add To Working copy 再点击提交 2. 上传第三方库时 默认SVN是忽略.a文件的要找到.a文件把他设置成不是忽略的通 ...
- 团队作业week2-软件分析和用户需求调查
我们的团队选择评定的软件是必应词典(iphone版)和使用较多的有道词典(iphone版) 类别 描述 评分(Bing) 评分(有道) 功能 核心功能1:词典 顾名思义,作为一款词典类 ...