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 ...
随机推荐
- [转载]寻找两个有序数组中的第K个数或者中位数
http://blog.csdn.net/realxie/article/details/8078043 假设有长度分为为M和N的两个升序数组A和B,在A和B两个数组中查找第K大的数,即将A和B按升序 ...
- 转战farbox
好久没更新博客了,感觉在博客园这种技术为主的博客里面写太多东西写得太杂了,平时的阅读体验非常糟糕,我一直都是一个喜欢记录的人,以前经常有在笔记本上写日记的习惯,但是自从用了网上博客之后,好像就再也没有 ...
- javaScript数据类型与typeof操作符
1,typeof操作符. typeof操作符是用来检测变量的数据类型.使用:typeof 变量名;返回以下字符串: 字符串 描述 undefined 未定义 boolean 布尔值 string 字 ...
- 顺序图(Sequence Diagram)
顺序图(Sequence Diagram)对系统的动态方面来建模. 顺序图是强调消息时间顺序的交互图. 协作图则是强调接收和发送消息的对象的结构组织的交互图 如何对动态方面建模? 所谓动态文面,即 ...
- Android UI开发第四十一篇——墨迹天气3.0引导界面及动画实现
周末升级了墨迹天气,看着引导界面做的不错,模仿一下,可能与原作者的代码实现不一样,但是实现的效果还是差不多的.先分享一篇以前的文章,android动画的基础知识,<Android UI开发第十二 ...
- css的两种引用方式 link和@import
学习web开发的最大乐趣就是不断的发现自己以前不曾见过的东西,这些东西对于我来说是那么的新鲜有趣. 比如说今天偶尔研究别人的网站,就发现了有趣的东东. 当点开此网页的css时(这个css文件命名方式就 ...
- DDD:关于模型的合法性,Entity.IsValid()合理吗?
背景 见过很多框架(包括我自己的)都会在实体的定义中包含一个IsValid()方法,用来判断实体的合法性,是否应该这样设计呢?本文就这个问题介绍一点想法,希望大家多批评. 实体能否处于“非法”状态? ...
- [IR] Ranking - top k
PageRanking 通过: Input degree of link "Flow" model - 流量判断喜好度 传统的方式又是什么呢? Every term在某个doc中的 ...
- [转载]Windows 2012 R2安装SharePoint 2013 手动安装工具软件
之前介绍过在window 2012中安装SharePoint 2013,这次,借着SharePoint 2013 sp1补丁发布之际,介绍下在window 2012 r2中安装SharePoint 2 ...
- iOS性能优化之内存管理:Analyze、Leaks、Allocations的使用和案例代码
最近接了个小任务,和公司的iOS小伙伴们分享下instruments的具体使用,于是有了这篇博客...性能优化是一个很大的话题,这里讨论的主要是内存泄露部分. 一. 一些相关概念 很多人应该比较了解这 ...