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 0;
            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 = 0; 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

转载于:https://www.cnblogs.com/ASPNET2008/p/3291357.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值