Follow me to learn what is Unit of Work pattern
Introduction
A Unit of Work is a combination of several actions that will be grouped into a transaction. This means that all actions inside a unit of work are committed or rolled back. The advantage of using a unit of work is that multiple save actions to multiple repositories can be grouped as a unit.
The image above shows that the Unit of Work is the top-level component to be used. Each Unit Of Work contains its own DbContext instance.
Road Map
Part1:Follow me to learn how to use mvc template
Part2:Follow me to learn what is repository pattern
Part3:Follow me to learn what is Unit of Work pattern
How to implement Unit Of Work
Now, let us to start to implement unit of work
Step1: Create interface IUnitOfWork
public interface IUnitOfWork:IDisposable
{
bool IsCommitted { get; set; }
int Commit();
void Rollback();
}
Step 2: Concrete Implementation of IUnitOfWork
public class UnitOfWorkBase : IUnitOfWork
{
public UnitOfWorkBase()
{ }
private Dictionary<Type, object> _repositories;
private ObjectContext _context=null;
internal ObjectContext Context
{
get { return _context; }
}
public bool IsCommitted { get; set; }
public RepositoryBase<TSet> GetRepository<TSet>() where TSet : class, new()
{
if (null == _repositories) _repositories = new Dictionary<Type, object>();
if (_repositories.Keys.Contains(typeof(TSet)))
return _repositories[typeof(TSet)] as RepositoryBase<TSet>; var repository = new RepositoryBase<TSet>(true,this.Context); _repositories.Add(typeof(TSet), repository);
if (null == _context) _context = repository.Repository.Context;
return repository;
} public int Commit()
{
if (IsCommitted) return ;
return this.Context.SaveChanges();
}
public void Rollback()
{
this.IsCommitted = true;
this.Context.Dispose();
}
public void Dispose()
{
if (!this.IsCommitted)
{
this.Context.SaveChanges();
}
this.Context.Dispose();
} }
Let’s take a look at our IRepository GetRepository<TSet>() method here in our UnitOfWork implementation. Here we are storing all the activated instances of repositories for each and every requests. One there is a request for a given repository we will first check to see if our Container has been created, if not, will go ahead and create our container. Next, we’ll scan our container to see if the requested repository instance has already been created, if it has, then will return it, if it hasn’t, we will activate the requested repository instance, store it in our container, and then return it. If it helps, you can think of this as lazy loading our repository instances, meaning we are only creating repository instances on demand, this allows us to only create the repository instances needed for a given web request.
How to use?
Demo
public ObjectModel.RoleAction DeleteAndInsertRoleAction(ObjectModel.RoleAction model, ObjectModel.TreeViewModel TreeView)
{
using (var dao = new UnitOfWorkBase())
{
var repositoryNew = dao.GetRepository<RoleAction>();
var oldRecords = repositoryNew.Query(p => p.IsActive && p.RoleInfoId == model.RoleInfoId).ToList();
int roleid = model.RoleInfoId;
List<string> newActionIds = TreeView.NodeItems.Where(item => item.Checked)
.SelectMany(item => item.Items.Where(a => a.Checked))
.Select(a => a.Value)
.ToList();
var deleteRecords = oldRecords.Where(p => !newActionIds.Contains(p.ActionInfoId.ToString())).ToList();
var insertRecords = newActionIds.Where(p => !oldRecords.Select(q => q.ActionInfoId.ToString()).Contains(p)).ToList();
try
{ foreach (var item in deleteRecords)
{
repositoryNew.Delete(item);
}
for (int i = ; i < insertRecords.Count; i++)
{
RoleAction roleAction = new RoleAction();
roleAction.RoleInfoId = roleid;
roleAction.ActionInfoId = Convert.ToInt32(insertRecords[i]);
repositoryNew.Insert(roleAction);
}
}
catch (Exception ex)
{
dao.Rollback();
throw ex;
}
}
return model;
}
Note:
refer to http://blog.catenalogic.com/post/2013/02/27/Entity-Framework-Unit-of-Work-and-repositories.aspx
Follow me to learn what is Unit of Work pattern的更多相关文章
- Follow me to learn what is repository pattern
Introduction Creating a generic repository pattern in an mvc application with entity framework is th ...
- Follow me to learn how to use mvc template
Introduction After having gone through many project: Project A Project B Project C I start to write ...
- Using the Repository and Unit Of Work Pattern in .net core
A typical software application will invariably need to access some kind of data store in order to ca ...
- 10 Unit Testing and Automation Tools and Libraries Java Programmers Should Learn
转自:https://javarevisited.blogspot.com/2018/01/10-unit-testing-and-integration-tools-for-java-program ...
- C# Note36: .NET unit testing framework
It’s usually good practice to have automated unit tests while developing your code. Doing so helps y ...
- Fluent Validation + NInject3 + MVC5
Fluent Validation + NInject + MVC - Why & How : Part 1 http://fluentvalidation.codeplex.com/ htt ...
- Spock - Document -02 - Spock Primer
Spock Primer Peter Niederwieser, The Spock Framework TeamVersion 1.1 This chapter assumes that you h ...
- Entity Framework 6 (7) vs NHibernate 4: DDD perspective(纯净DDD很难很难...)
There is quite a bit of Entity Framework vs NHibernate comparisons on the web already, but all of th ...
- [Jest] Test JavaScript with Jest
Let's learn how to unit test your JavaScript with Jest, a JavaScript unit testing framework from Fac ...
随机推荐
- saiku执行速度优化二
上一篇文章介绍了添加filter可以加快查询速度.下面继续分析: 下面这个MDX语句: WITH SET [~FILTER] AS {[create_date].[create_date].[--]} ...
- Ubuntu apt命令
http://www.tecmint.com/useful-basic-commands-of-apt-get-and-apt-cache-for-package-management/ apt-ca ...
- PHP cURL应用实现模拟登录与采集使用方法详解
对于做过数据采集的人来说,cURL一定不会陌生.虽然在PHP中有file_get_contents函数可以获取远程链接的数据,但是它的可控制性太差了,对于各种复杂情况的采集情景,file_get_co ...
- CENTOS 基础指令——查看系统环境
1.查看内核版本 # cat /proc/version # uname -a # uname -r 2.查看linux版本 # cat /etc/issue # cat /etc/redhat-re ...
- MSSQL大数据量增加字段耗时对比
单个数据表记录数为1亿4千万条. 一.测试同时增加两个允许为空的字段. ALTER TABLE [dbo].[XRecord] ADD [sType] int,[cType] int GO 开始时间: ...
- 【转】NPOI 单元格级别应用
NPOI 单元格级别应用A HSSFWorkbook hssfworkbook = new HSSFWorkbook();//初始化一个新的HSSFWorkbook实例 //#region 1.创建一 ...
- _set_invalid_parameter_handler异常处理函数
VS2005之后的版本,微软增加了一些新的异常机制,新机制在出现错误时默认不通知应用程序,这时程序就崩溃了.所以这种情况下,必须调用_set_invalid_parameter_handler._se ...
- xdebug调试一直等待连接
调试php时一般会启动浏览器,地址栏里一般是 index.php?XDEBUG_SESSION_START=xxx xxx表示调试的ide_key. 开了代理没有关,结果调试时一直无法连上,折腾了好久 ...
- AssetBundle系列——游戏资源打包(二)
本篇接着上一篇.上篇中说到的4步的代码分别如下所示: (1)将资源打包成assetbundle,并放到自定目录下 using UnityEditor; using UnityEngine; using ...
- 简单的session共享的封装
目的 session存储在缓存服务器上(各种缓存服务器上均可,本文以memcached为例),但对开发者来说,他不用关注,只需要调用request.getSession()方法即可获取到session ...