EF基类封装

Posted lizhenhong

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了EF基类封装相关的知识,希望对你有一定的参考价值。

1、MyDbContext

public partial class MyDbContext: DbContext
    {
        public MyDbContext()
            : base("name=MyEntities")
        {
        }
        public virtual DbSet<user> user{ get; set; }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }
}

2、MyDbContextFactory

  public class MyDbContextFactory
    {
        /// <summary>
        /// 获取线程唯一上下文
        /// </summary>
        /// <returns></returns>
        public static MyDbContext GetCurrentDbContext()
        {
            //线程在内存上下文
            TaosDbContext myDbContext = CallContext.GetData("MyCurrentDbContext") as MyDbContext;

            if (myDbContext== null)
            {
                myDbContext= new MyDbContext();
                CallContext.SetData("MyCurrentDbContext", myDbContext);
            }
            return myDbContext;
        }
    }

  

 

3、GenericRepository

    public class GenericRepository<TEntity> where TEntity : class
    {
        public MyDbContext context { get; private set; }
        public DbSet<TEntity> dbSet { get; private set; }
        public GenericRepository()
        {
            this.context = MyDbContextFactory.GetCurrentDbContext();
            this.dbSet = context.Set<TEntity>();
        }

        public void SaveChanges()
        {
            if (this.context != null)
            {
                this.context.SaveChanges();
            }
        }

        private DbContextTransaction beginTransaction;
        public void BeginTransaction()
        {
            this.beginTransaction = context.Database.BeginTransaction();
        }

        public void Commit()
        {
            if (this.beginTransaction == null)
                return;

            try
            {
                this.SaveChanges();
                this.beginTransaction.Commit();
            }
            catch (Exception ex)
            {
                if (this.beginTransaction != null)
                    this.beginTransaction.Rollback();
                throw;
            }
            finally
            {
                if (this.beginTransaction != null)
                    this.beginTransaction.Dispose();
                this.beginTransaction = null;
            }
        }

        #region EF 增删改查 

        /// <summary>
        /// 插入
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public TEntity Insert(TEntity entity)
        {
            this.dbSet.Add(entity);
            return entity;
        }

        /// <summary>
        /// 批量插入
        /// </summary>
        /// <param name="entitys"></param>
        /// <returns></returns>
        public IEnumerable<TEntity> InsertRange(IEnumerable<TEntity> entitys)
        {
            this.dbSet.AddRange(entitys);
            return entitys;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public void Delete(TEntity entity)
        {
            context.Entry<TEntity>(entity).State = EntityState.Deleted;
        }

        /// <summary>
        /// 删除 根据条件删除
        /// </summary>
        /// <param name="whereExpression"></param>
        public void Delete(Expression<Func<TEntity, bool>> whereExpression)
        {
            var entity = this.dbSet.Where(whereExpression).FirstOrDefault();
            if (entity != null)
            {
                Delete(entity);
            }
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="entitys"></param>
        /// <returns></returns>
        public void DeleteRange(IEnumerable<TEntity> entitys)
        {
            this.dbSet.RemoveRange(entitys);
        }

        /// <summary>
        /// 批量删除 根据条件删除
        /// </summary>
        /// <param name="entitys"></param>
        /// <returns></returns>
        public void DeleteRange(Expression<Func<TEntity, bool>> whereExpression)
        {
            var entitys = this.dbSet.Where(whereExpression);
            if (entitys != null)
            {
                DeleteRange(entitys);
            }
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public void Update(TEntity entity)
        {
            this.dbSet.Attach(entity);
            context.Entry(entity).State = EntityState.Modified;
        }
        /// <summary>
        /// 批量更新
        /// </summary>
        /// <param name="entitys"></param>
        /// <returns></returns>
        public IEnumerable<TEntity> Update(IEnumerable<TEntity> entitys)
        {
            foreach (var entity in entitys)
            {
                Update(entity);
            }
            return entitys;
        }

        /// <summary>
        /// 单表分页
        /// </summary>
        /// <param name="PageIndex"></param>
        /// <param name="PageSize"></param>
        /// <param name="TotalCount"></param>
        /// <param name="whereExpression"></param>
        /// <param name="whereOrderBy"></param>
        /// <returns></returns>
        public List<TEntity> Pagination(int PageIndex, int PageSize, out int TotalCount, Expression<Func<TEntity, bool>> whereExpression, Expression<Func<TEntity, bool>> whereOrderBy = null)
        {
            var querys = this.dbSet.Where(whereExpression);
            if (whereOrderBy != null)
            {
                querys = querys.OrderByDescending(whereOrderBy);
            }
            TotalCount = querys.Count();
            return querys.Skip(PageSize * (PageIndex - 1)).Take(PageSize).ToList() ?? null;
        }
        #endregion
    }

  

以上是关于EF基类封装的主要内容,如果未能解决你的问题,请参考以下文章

BIM工程信息管理系统-EF实体框架数据操作基类

EF继承/基类问题

EF添加关联的提示问题:映射从第 260 行开始的片段时有问题:

EF增删查改基类

框架搭建与EF常用基类实现

VSCode自定义代码片段14——Vue的axios网络请求封装