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方法 call()和apply()的用法

    先上代码: apply()方法示例 /*定义一个人类*/ function Person(name,age) { this.name=name; this.age=age; } /*定义一个学生类*/ ...

  2. apache下virtualhost与location合用配置转发SVN控制访问

    使用apache的文件系统配置 使用virtualhost 实现location 重定向 NameVirtualHost *:80 <VirtualHost *:80> ServerNam ...

  3. 用gameMaker做个小游戏

    看下面这个课程链接,半小时学会 http://study.163.com/course/courseMain.htm?courseId=352004#/courseMain 这是我做的:http:// ...

  4. POJ 1012 Joseph

    Joseph Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 44650   Accepted: 16837 Descript ...

  5. 如何在IIS7或IIS7.5中导入导出站点及应用程序池.

    为实现负载平衡,我们可能会使用多个WEB服务器,也就会需要给多个IIS配置同样的站点和应用程序池.那么我们需要一个一个的重新建吗?当然不用,我们只需要一些简单的命令就可以在IIS7(Windows S ...

  6. [CS231n-CNN] Backpropagation(反向传播算法)

    课程主页:http://cs231n.stanford.edu/ 上节讲到loss function: 引出了求导数使得loss function减小. -Back Propagation :梯度下降 ...

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

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

  8. [转载]在线文档预览方案-Office Web Apps

    最近在做项目时,要在手机端实现在线文档预览的功能.于是百度了一下实现方案,大致是将文档转换成pdf,然后在通过插件实现预览.这些方案没有具体实现代码,也没有在线预览的地址,再加上项目时间紧迫.只能考虑 ...

  9. 受限玻尔兹曼机(RBM)学习笔记(八)RBM 的评估

      去年 6 月份写的博文<Yusuke Sugomori 的 C 语言 Deep Learning 程序解读>是囫囵吞枣地读完一个关于 DBN 算法的开源代码后的笔记,当时对其中涉及的算 ...

  10. [git]用pelican搞一个自己的blog(已完成)

    pelican Pelican Static Site Generator, Powered by Python:Pelican是python语言写的静态网站生成器.因为我一直打算用github pa ...