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 ...
随机推荐
- Git回滚远程版本
摘要: 原创出处:www.bysocket.com 泥瓦匠BYSocket 希望转载,保留摘要,谢谢! “房子是租的 但生活不是” 1.故事的开始 远程master分支下代码被不小心提交了很多垃圾代码 ...
- 用对 gitignore
使用 git 做代码管理工具时,设置 gitignore 是必不可少的流程,一些系统或者 IDE 会在目录下生成与项目不相关的文件,而这些文件我们不期望被提交到仓库之中.理解 gitignore 的 ...
- git 在提交之前撤销add操作
问题 在使用git时,在未添加.ignore文件前使用 git add . 将所有文件添加到库中,不小心将一些不需要加入版本库的文件加到了版本库中.由于此时还没有提交所以不存在HEAD版本,不能使用 ...
- CreateProcessAsUser,C#写的windows服务弹框提示消息或者启动子进程
服务(Service)对于大家来说一定不会陌生,它是Windows 操作系统重要的组成部分.我们可以把服务想像成一种特殊的应用程序,它随系统的“开启-关闭”而“开始-停止”其工作内容,在这期间无需任何 ...
- angularjs + seajs构建Web Form前端(三) -- 兼容easyui
回顾 在上一章中使用了angular实现了ajax form和树形结构,经过以上两章对于angular的大致使用,对于angular也有了初步的认识,接下来的内容只会对angular的一些用法做简单的 ...
- zmq 学习笔记
0. PUB/SUB, XPUB/XSUB filtering happens at publisher sides when sockets are using a connected protoc ...
- oracle/sqlserver 递归
1.Oracle递归查询 2.SqlServer递归查询 with cte as ( select t.id,t.name,t.parentId from dbo.Department t where ...
- HANA Studio中修改默认查询结果只显示1000行
- 使用NPOI导出excel
NPOI下载地址http://npoi.codeplex.com/releases 从项目中引用NPOI.bll和NPOI.OOXML.bll 引用命名控件 using NPOI.HSSF.UserM ...
- 优化LibreOffice如此简单
对于开源软件的支持者和粉丝来说,LibreOffice 无疑是 Microsoft Office 的最佳替代品,而且它已在过去的许多版本迭代中迎来了许多巨大改进.然而,通过用户的手动配置,我们还是有办 ...