真爱无限的知识驿站

学习积累技术经验,提升自身能力

.Net框架搭建之2、SQL Server MEF依赖注入 MVC Repository框架_part3

UnitOfWorkContextBase.cs

/* ==============================================================================
 * 功能描述:UnitOfWorkContextBase  
 * 创 建 者:蒲奎民
 * 创建日期:2016-08-29 10:59:20
 * CLR Version :4.0.30319.42000
 * ==============================================================================*/
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Validation;
using System.Data.SqlClient;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace InjectExample.Component
{
    /// <summary>
    ///     单元操作实现基类
    /// </summary>
    public abstract class UnitOfWorkContextBase : IUnitOfWorkContext
    {
        /// <summary>
        /// 获取 当前使用的数据访问上下文对象
        /// </summary>
        protected abstract DbContext Context { get; }
        /// <summary>
        ///     获取 当前单元操作是否已被提交
        /// </summary>
        public bool IsCommitted { get; private set; }
        public DbContext DbContext { get { return Context; } }
        /// <summary>
        ///     提交当前单元操作的结果
        /// </summary>
        /// <param name="validateOnSaveEnabled">保存时是否自动验证跟踪实体</param>
        /// <returns></returns>
        public int Commit(bool validateOnSaveEnabled = false)
        {
            //validateOnSaveEnabled=true时莫名其妙报错,暂时去掉
            validateOnSaveEnabled = false;
            if (IsCommitted)
            {
                return 0;
            }
            try
            {
                int result = Context.SaveChanges(validateOnSaveEnabled);
                IsCommitted = true;
                return result;
            }
            catch (DbEntityValidationException ex)
            {
                var entry = ex.EntityValidationErrors.First().Entry;
                var err = ex.EntityValidationErrors.First().ValidationErrors.First();
                var msg = err.ErrorMessage;
                try
                {
                    var displayName = entry.Entity.GetType().GetProperty(err.PropertyName).GetPropertyDisplayName();
                    msg = string.Format(msg, displayName, entry.CurrentValues.GetValue<object>(err.PropertyName));
                }
                catch (Exception)
                {
                }
                throw new Exception(msg);
            }
            catch (DbUpdateException e)
            {
                if (e.InnerException != null && e.InnerException.InnerException is SqlException)
                {
                    var sqlEx = e.InnerException.InnerException as SqlException;
                    //string msg = DataHelper.GetSqlExceptionMessage(sqlEx.Number);
                    throw sqlEx; //PublicHelper.ThrowDataAccessException("提交数据更新时发生异常:" + msg, sqlEx);
                }
                throw;
            }
        }
        /// <summary>
        ///  把当前单元操作标记成未提交状态,发生错误时,不能回滚事务,不要调用!
        /// </summary>
        public void Rollback()
        {
            IsCommitted = false;
        }
        public void Dispose()
        {
            //if (!IsCommitted)
            //{
            //    Commit();
            //}
            //if (Context != null)
            //    Context.Dispose();
        }
        /// <summary>
        ///   为指定的类型返回 System.Data.Entity.DbSet,这将允许对上下文中的给定实体执行 CRUD 操作。
        /// </summary>
        /// <typeparam name="TEntity"> 应为其返回一个集的实体类型。 </typeparam>
        /// <returns> 给定实体类型的 System.Data.Entity.DbSet 实例。 </returns>
        public DbSet<TEntity> Set<TEntity>() where TEntity : class// EntityBase<TKey>
        {
            return Context.Set<TEntity>();
        }
        /// <summary>
        ///     注册一个新的对象到仓储上下文中
        /// </summary>
        /// <typeparam name="TEntity"> 要注册的类型 </typeparam>
        /// <param name="entity"> 要注册的对象 </param>
        public void RegisterNew<TEntity>(TEntity entity) where TEntity : class// EntityBase<TKey>
        {
            EntityState state = Context.Entry(entity).State;
            if (state == EntityState.Detached)
            {
                Context.Entry(entity).State = EntityState.Added;
            }
            IsCommitted = false;
        }
        /// <summary>
        ///     批量注册多个新的对象到仓储上下文中
        /// </summary>
        /// <typeparam name="TEntity"> 要注册的类型 </typeparam>
        /// <param name="entities"> 要注册的对象集合 </param>
        public void RegisterNew<TEntity>(IEnumerable<TEntity> entities) where TEntity : class// EntityBase<TKey>
        {
            try
            {
                Context.Configuration.AutoDetectChangesEnabled = false;
                foreach (TEntity entity in entities)
                {
                    RegisterNew<TEntity>(entity);
                }
            }
            finally
            {
                Context.Configuration.AutoDetectChangesEnabled = true;
            }
        }
        public void RegisterModified<TEntity>(IEnumerable<TEntity> entities) where TEntity : class// EntityBase<TKey>
        {
            try
            {
                Context.Configuration.AutoDetectChangesEnabled = false;
                foreach (TEntity entity in entities)
                {
                    EntityState state = Context.Entry(entity).State;
                    if (state == EntityState.Detached)
                    {
                        Context.Entry(entity).State = EntityState.Modified;
                    }
                    IsCommitted = false;
                }
            }
            finally
            {
                Context.Configuration.AutoDetectChangesEnabled = true;
  &nbs

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

Powered By Z-BlogPHP 1.7.3

Copyright 2024-2027 pukuimin Rights Reserved.
粤ICP备17100155号