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的更多相关文章

  1. Follow me to learn what is repository pattern

    Introduction Creating a generic repository pattern in an mvc application with entity framework is th ...

  2. 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 ...

  3. 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 ...

  4. 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 ...

  5. C# Note36: .NET unit testing framework

    It’s usually good practice to have automated unit tests while developing your code. Doing so helps y ...

  6. Fluent Validation + NInject3 + MVC5

    Fluent Validation + NInject + MVC - Why & How : Part 1 http://fluentvalidation.codeplex.com/ htt ...

  7. Spock - Document -02 - Spock Primer

    Spock Primer Peter Niederwieser, The Spock Framework TeamVersion 1.1 This chapter assumes that you h ...

  8. 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 ...

  9. [Jest] Test JavaScript with Jest

    Let's learn how to unit test your JavaScript with Jest, a JavaScript unit testing framework from Fac ...

随机推荐

  1. Javascript类继承-机制-代码Demo【原创】

    最近看到<Javascript设计模式>,对js模拟的”继承方式“有了更深一步的了解,虽然之前也总是用到prototype.new ,但只是知其然不知所以然,现在将类继承的方法整理如下,暂 ...

  2. 从javascript一道闭包面试题说开去

    这道题目比较经典了: var a = 1; function test(){ a = 2; return function(){ console.log(a); } var a = 3; } test ...

  3. MFC下调用控制台和控制台下MFC库的支持

    1.MFC下调用控制台 在CWinApp的InitInstance中对话框的DoModal之前加入 AllocConsole(); // 开辟控制台 SetConsoleTitle(_T(" ...

  4. android 隐藏标题栏的方法

    1:单个activity里 onCreate() { super.onCreate(); requestWindowFeature(Window.FEATURE_NO_TITLE); setConte ...

  5. (转)linux内核虚拟文件系统浅析

    转自http://hi.baidu.com/_kouu/item/4e9db87580328244ef1e53d0 ###### 虚拟文件系统(VFS)在我看来, "虚拟"二字主要 ...

  6. JavaScript 中介者模式与观察者模式有何不同?

    http://addyosmani.com/resources/essentialjsdesignpatterns/book/#detailmvp 感觉二者非常像,都是pub/sub机制,如何进行区分 ...

  7. NGUI 修改Shader支持灰色滤镜

    之前有人做过,不过效率不高: http://blog.csdn.net/onerain88/article/details/12197277  他的代码: fixed4 frag (v2f i) : ...

  8. DDD:《实现领域驱动》拾贝(待续)

    Design is not just what it looks like and feels like. Design is how it works.

  9. 使用 GistBox 轻松组织和管理你的代码片段

    GistBox 用简便的方式来组织和管理代码片段.你的代码会保存到云端进行备份,再也不用担心迷失在杂乱的代码片段中.GistBox 是建立在标准的 HTML5 技术基础上.在旅途中或在办公室,你都可以 ...

  10. SQL Server技术问题之触发器优缺点

    优点: 1.强化约束:强制复杂业务的规则和要求,能实现比check语句更为复杂的约束. 2.跟踪变化:触发器可以侦测数据库内的操作,从而禁止数据库中未经许可的更新和变化. 3.级联运行:侦测数据库内的 ...