自己封装了一个EF的上下文类.,分享一下,顺便求大神指点

Posted 石涛涛

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了自己封装了一个EF的上下文类.,分享一下,顺便求大神指点相关的知识,希望对你有一定的参考价值。

技术分享
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Core.Objects;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Migrations;
using System.Data.Entity.Validation;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using EntityFramework.Extensions;
using System.Threading.Tasks;
//using log4net;
//using log4net.Core;

namespace _6._0Test
{
    /// <summary>
    /// 上下文静态实体类
    /// </summary>
    public static class DbContentEntity
    {
        /// <summary>
        /// 静态初始化
        /// </summary>
        static DbContentEntity()
        {
            if (string.IsNullOrEmpty(ConnectionString))
                return;
            if (_entities == null)
            {
                _entities = new TestEntities(ConnectionString);
                _entities.Configuration.ValidateOnSaveEnabled = false;
            }
            if (_entities.Database.Connection.State == ConnectionState.Closed && _entities.Database.Connection.State != ConnectionState.Connecting)
            {
                _entities.Database.Connection.Open();
            }
        }

        /// <summary>
        /// 静态连接字符串
        /// </summary>

        public static string ConnectionString
        {
            get { return  ConfigurationManager.ConnectionStrings["TestEntities"].ConnectionString; }
        }

        /// <summary>
        /// 静态实体
        /// </summary>
        private static TestEntities _entities;
        /// <summary>
        /// 对外实体
        /// </summary>
        public static TestEntities Entities
        {
            get
            {
                if (string.IsNullOrEmpty(ConnectionString))
                    return null;
                return _entities ?? (_entities = new TestEntities(ConnectionString));
            }
        }



    }

    /// <summary>
    /// 上下文类
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public abstract class ModelContext<T>  where T : class
    {
        //日志,可自行拓展
        //public static ILog Log = LogManager.GetLogger(typeof(T).Name);


        /// <summary>
        /// 返回上下文实体
        /// </summary>
        protected TestEntities Entities
        {
            get { return DbContentEntity.Entities; }
        }

        private DbSet<T> _model;
    
        protected  DbSet<T> Model
        {
            get { return _model ?? (_model = Entities.Set<T>()); }
        }



        #region                =====查询用方法=====

        /// <summary>
        /// 根据条件查询实体
        /// </summary>
        /// <param name="where">条件</param>
        /// <returns>实体</returns>
        public virtual T Get(Expression<Func<T, bool>> @where)
        {

            return Model.FirstOrDefault(where);


        }


        /// <summary>
        /// 根据条件查询实体(异步)
        /// </summary>
        /// <param name="where">条件</param>
        /// <returns>实体</returns>
        public async virtual  Task<T> GetAsync(Expression<Func<T, bool>> @where)
        {

            return await Model.FirstOrDefaultAsync(where);


        }

        /// <summary>
        /// 根据条件查询实体集合(需自行tolist,自行异步)
        /// </summary>
        /// <param name="where">查询条件</param>
        /// <returns></returns>
        public virtual IQueryable<T> GetList(Expression<Func<T, bool>> @where)
        {

            return Model.AsNoTracking().Where(where);

        }

        /// <summary>
        /// 根据条件查询实体集合(需自行tolist,自行异步)
        /// </summary>
        /// <param name="where">查询条件</param>
        /// <returns></returns>
        public async virtual Task<IQueryable<T>> GetListAsync(Expression<Func<T, bool>> @where)
        {

            return await Task.Run(()=>Model.AsNoTracking().Where(where));

        }


        /// <summary>
        /// 根据传进来的实体类型查询该实体的集合
        /// </summary>
        /// <typeparam name="TM">实体类型</typeparam>
        /// <param name="where">查询条件</param>
        /// <returns></returns>
        public virtual IQueryable<TM> GetList<TM>(Expression<Func<TM, bool>> @where) where TM : class
        {

            var model = Entities.Set<TM>();
            return  model.AsNoTracking().Where(where);

        }
        /// <summary>
        /// 根据传进来的实体类型查询该实体(异步)
        /// </summary>
        /// <typeparam name="TM">实体类型</typeparam>
        /// <param name="where">查询条件</param>
        /// <returns></returns>
        public async virtual Task<TM> GetAsync<TM>(Expression<Func<TM, bool>> @where) where TM : class
        {

            var model = Entities.Set<TM>();
            return await model.FirstOrDefaultAsync(where);

        }

        /// <summary>
        /// 根据条件查询实体数量
        /// </summary>
        /// <typeparam name="TM">实体类型</typeparam>
        /// <param name="where">查询条件</param>
        /// <returns></returns>
        public virtual int Cout<TM>(Expression<Func<TM, bool>> @where) where TM : class
        {
            try
            {
                var model = Entities.Set<TM>();
                return model.AsNoTracking().Count(where);
            }
            catch (DbEntityValidationException dbEx)
            {
                //Log.Error(dbEx + dbEx.Message);
                return -1;
            }
            catch (Exception ex)
            {
                //Log.Error(ex + ex.Message);
                return -1;
            }
        }

        /// <summary>
        /// 根据条件查询实体数量(异步)
        /// </summary>
        /// <typeparam name="TM">实体类型</typeparam>
        /// <param name="where">查询条件</param>
        /// <returns></returns>
        public async virtual Task<int>  CoutAsync<TM>(Expression<Func<TM, bool>> @where) where TM : class
        {
            try
            {
                var model = Entities.Set<TM>();
                return await model.AsNoTracking().CountAsync(where);
            }
            catch (DbEntityValidationException dbEx)
            {
                //Log.Error(dbEx + dbEx.Message);
                return -1;
            }
            catch (Exception ex)
            {
                //Log.Error(ex + ex.Message);
                return -1;
            }
        }
        /// <summary>
        /// 根据条件查询实体数量
        /// </summary>
        /// <param name="where"></param>
        /// <returns></returns>
        public async virtual Task<int> Count(Expression<Func<T, bool>> @where)
        {
            try
            {
                var model = Entities.Set<T>();
                return await model.AsNoTracking().CountAsync(where);
            }
            catch (DbEntityValidationException dbEx)
            {
                //Log.Error(dbEx + dbEx.Message);
                return -1;
            }
            catch (Exception ex)
            {
                //Log.Error(ex + ex.Message);
                return -1;
            }
        }

#endregion


        #region ====添加用方法====
        /// <summary>
        /// 添加实体
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public virtual bool Add(T m)
        {
            try
            {

                Model.Add(m);
                Entities.SaveChanges();
            }
            catch (DbEntityValidationException dbEx)
            {
                //Log.Error(dbEx + dbEx.Message);
                return false;
            }
            catch (Exception ex)
            {
                //Log.Error(ex + ex.Message);
                return false;
            }
            return true;
        }
        /// <summary>
        /// 添加实体(异步)
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public async virtual Task<bool> AddAsync(T m)
        {
            try
            {

                Model.Add(m);
                await  Entities.SaveChangesAsync();
            }
            catch (DbEntityValidationException dbEx)
            {
                //Log.Error(dbEx + dbEx.Message);
                return false;
            }
            catch (Exception ex)
            {
                //Log.Error(ex + ex.Message);
                return false;
            }
            return true;
        }

        /// <summary>
        /// 根据类型添加实体
        /// </summary>
        /// <typeparam name="TM"></typeparam>
        /// <param name="tm"></param>
        /// <returns></returns>
        public virtual bool Add<TM>(TM tm) where TM : class
        {
            try
            {
                var model = Entities.Set<TM>();
                model.Add(tm);
                Entities.SaveChanges();
            }
            catch (DbEntityValidationException dbex)
            {
                //Log.Error(dbex + dbex.Message);
                return false;
            }
            catch (Exception ex)
            {
                //Log.Error(ex + ex.Message);
                return false;
            }
            return true;
        }

        /// <summary>
        /// 批量添加实体
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public virtual bool AddRange(IEnumerable<T> m)
        {

            try
            {
                Model.AddRange(m);
                Entities.SaveChanges();
            }
            catch (DbEntityValidationException dbEx)
            {
                //Log.Error(dbEx + dbEx.Message);
                return false;
            }
            catch (Exception ex)
            {
                //Log.Error(ex + ex.Message);
                return false;
            }
            return true;
        }
        /// <summary>
        /// 批量添加实体(异步)
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public async virtual Task<bool> AddRangeAsync(IEnumerable<T> m)
        {

            try
            {
                Model.AddRange(m);
                await Entities.SaveChangesAsync();
            }
            catch (DbEntityValidationException dbEx)
            {
                //Log.Error(dbEx + dbEx.Message);
                return false;
            }
            catch (Exception ex)
            {
                //Log.Error(ex + ex.Message);
                return false;
            }
            return true;
        }

        #endregion


        #region ====修改用方法====
        /// <summary>
        /// 修改实体
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public virtual bool Update(T t)
        {

            try
            {

                Model.Attach(t);
                Entities.Entry(t).State = EntityState.Modified;
                Entities.SaveChanges();
            }
            catch (DbEntityValidationException dbEx)
            {
                //Log.Error(dbEx + dbEx.Message);
                return false;
            }
            catch (Exception ex)
            {
                //Log.Error(ex + ex.Message);
                return false;
            }
            return true;
        }

        /// <summary>
        /// 修改实体(异步)
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public async virtual Task<bool> UpdateAsync(T t)
        {

            try
            {

                Model.Attach(t);
                Entities.Entry(t).State = EntityState.Modified;
                await Entities.SaveChangesAsync();
            }
            catch (DbEntityValidationException dbEx)
            {
                //Log.Error(dbEx + dbEx.Message);
                return false;
            }
            catch (Exception ex)
            {
                //Log.Error(ex + ex.Message);
                return false;
            }
            return true;
        }
        /// <summary>
        /// 根据类型修改实体
        /// </summary>
        /// <typeparam name="TM"></typeparam>
        /// <param name="tm"></param>
        /// <returns></returns>
        public virtual bool Update<TM>(TM tm) where TM : class
        {
            try
            {
                var model = Entities.Set<TM>();
                model.Attach(tm);
                Entities.Entry(tm).State = EntityState.Modified;
                Entities.SaveChanges();
            }
            catch (DbEntityValidationException dbEx)
            {
                //Log.Error(dbEx + dbEx.Message);
                return false;
            }
            catch (Exception ex)
            {
                //Log.Error(ex + ex.Message);
                return false;
            }
            return true;
        }

        /// <summary>
        /// 批量更新数据
        /// </summary>
        /// <param name="where">更新数据的条件 如:u => u.FirstName == "firstname"</param>
        /// <param name="ex">更新的值 如:u=>new User{FirstName = "newfirstname"}</param>
        /// <returns>返回影响的条数</returns>
        public virtual int Update(Expression<Func<T, bool>> @where, Expression<Func<T, T>> ex)
        {
            try
            {
                return Model.Where(where).Update(ex);
            }
            catch (DbEntityValidationException dbEx)
            {
                //Log.Error(dbEx + dbEx.Message);
                return -1;
            }
            catch (Exception e)
            {
               // Log.Error(e + e.Message);
                return -1;
            }
        }

        /// <summary>
        /// 批量更新数据(异步)
        /// </summary>
        /// <param name="where">更新数据的条件 如:u => u.FirstName == "firstname"</param>
        /// <param name="ex">更新的值 如:u=>new User{FirstName = "newfirstname"}</param>
        /// <returns>返回影响的条数</returns>
        public async virtual  Task<int> UpdateAsync(Expression<Func<T, bool>> @where, Expression<Func<T, T>> ex)
        {
            try
            {
                return  await  Model.Where(where).UpdateAsync(ex);
            }
            catch (DbEntityValidationException dbEx)
            {
                //Log.Error(dbEx + dbEx.Message);
                return -1;
            }
            catch (Exception e)
            {
                // Log.Error(e + e.Message);
                return -1;
            }
        }

       /// <summary>
       /// 添加或者修改实体(无则添加,有则修改)
       /// </summary>
       /// <param name="m"></param>
       /// <returns></returns>
        public virtual bool AddOrUpdate(T[] m)
        {
            try
            {
                Model.AddOrUpdate(m);
                Entities.SaveChanges();
            }
            catch (DbEntityValidationException dbEx)
            {
               // Log.Error(dbEx + dbEx.Message);
                return false;
            }
            catch (Exception ex)
            {
                //Log.Error(ex + ex.Message);
                return false;
            }
            return true;
        }


        /// <summary>
        /// 添加或者修改实体(无则添加,有则修改,异步)
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public async virtual Task<bool> AddOrUpdateAsync(T[] m)
        {
            try
            {
                Model.AddOrUpdate(m);
                await Entities.SaveChangesAsync();
            }
            catch (DbEntityValidationException dbEx)
            {
                // Log.Error(dbEx + dbEx.Message);
                return false;
            }
            catch (Exception ex)
            {
                //Log.Error(ex + ex.Message);
                return false;
            }
            return true;
        }

        #endregion


        #region ===事务====
        /// <summary>
        /// 运行基本事务,返回bool值
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>

        protected bool RunTransaction(Action<DbSet<T>> model)
        {

            using (var transaction = Entities.Database.BeginTransaction())
            {
                try
                {
                    model.Invoke(Model);
                    Entities.SaveChanges();
                    transaction.Commit();
                    return true;
                }
                catch (DbEntityValidationException dbEx)
                {
                    //Log.Error("EXEC RunTransaction Error:" + dbEx + dbEx.Message);
                    return false;
                }
                catch (Exception ex)
                {
                    //Log.Error("EXEC RunTransaction Error:" + ex + ex.Message);
                    transaction.Rollback();
                    return false;

                }
            }

        }
        /// <summary>
        /// 运行基本事务,返回bool值(异步)
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>

        protected async Task<bool> RunTransactionAsync(Action<DbSet<T>> model)
        {

            using (var transaction = Entities.Database.BeginTransaction())
            {
                try
                {
                    model.Invoke(Model);
                    await Entities.SaveChangesAsync();
                    transaction.Commit();
                    return true;
                }
                catch (DbEntityValidationException dbEx)
                {
                    //Log.Error("EXEC RunTransaction Error:" + dbEx + dbEx.Message);
                    return false;
                }
                catch (Exception ex)
                {
                    //Log.Error("EXEC RunTransaction Error:" + ex + ex.Message);
                    transaction.Rollback();
                    return false;

                }
            }

        }
        #endregion

        #region======删除用方法====
        /// <summary>
        /// 删除实体
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public virtual bool Remove(T t)
        {
            try
            {
                Model.Remove(t);
                Entities.SaveChanges();

            }
            catch (DbEntityValidationException dbEx)
            {
                //Log.Error(dbEx + dbEx.Message);
                return false;
            }
            catch (Exception ex)
            {
                //Log.Error(ex + ex.Message);
                return false;
            }
            return true;

        }

        /// <summary>
        /// 删除实体(异步)
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public async virtual Task<bool> RemoveAsync(T t)
        {
            try
            {
                Model.Remove(t);
                await Entities.SaveChangesAsync();

            }
            catch (DbEntityValidationException dbEx)
            {
                //Log.Error(dbEx + dbEx.Message);
                return false;
            }
            catch (Exception ex)
            {
                //Log.Error(ex + ex.Message);
                return false;
            }
            return true;

        }

        /// <summary>
        /// 根据类型删除实体
        /// </summary>
        /// <typeparam name="TM"></typeparam>
        /// <param name="m"></param>
        /// <returns></returns>
        public virtual bool Remove<TM>(TM m) where TM : class
        {
            try
            {
                var model = Entities.Set<TM>();
                model.Remove(m);
                Entities.SaveChanges();

            }
            catch (DbEntityValidationException dbEx)
            {
                //Log.Error(dbEx + dbEx.Message);
                return false;
            }
            catch (Exception ex)
            {
                //Log.Error(ex + ex.Message);
                return false;
            }
            return true;
        }


        /// <summary>
        ///批量删除实体
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public virtual int RemoveRange(IEnumerable<T> m)
        {

            try
            {
                Model.RemoveRange(m);
                return Entities.SaveChanges();
            }
            catch (DbEntityValidationException dbEx)
            {
                //Log.Error(dbEx + dbEx.Message);
                return -1;
            }
            catch (Exception ex)
            {
                //Log.Error(ex + ex.Message);
                return -1;
            }

        }

        /// <summary>
        ///批量删除实体(异步)
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public async virtual  Task<int> RemoveRangeAsync(IEnumerable<T> m)
        {

            try
            {
                Model.RemoveRange(m);
                return await Entities.SaveChangesAsync();
            }
            catch (DbEntityValidationException dbEx)
            {
                //Log.Error(dbEx + dbEx.Message);
                return -1;
            }
            catch (Exception ex)
            {
                //Log.Error(ex + ex.Message);
                return -1;
            }

        }


        /// <summary>
        /// 根据类型批量删除实体
        /// </summary>
        /// <typeparam name="TM"></typeparam>
        /// <param name="tmMs"></param>
        /// <returns></returns>
        public virtual int RemoveRange<TM>(IEnumerable<TM> tmMs) where TM : class
        {
            try
            {
                var model = Entities.Set<TM>();
                model.RemoveRange(tmMs);
                return Entities.SaveChanges();
            }
            catch (DbEntityValidationException dbEx)
            {
                //Log.Error(dbEx + dbEx.Message);
                return -1;
            }
            catch (Exception ex)
            {
                //Log.Error(ex + ex.Message);
                return -1;

            }

        }
        #endregion

    }

}
技术分享

以上是关于自己封装了一个EF的上下文类.,分享一下,顺便求大神指点的主要内容,如果未能解决你的问题,请参考以下文章

面试中如果这样写二分查找!

ef核心 - 如何将类映射的多个变体放到同一个表中

Go面试中如果这样写二分查找!

EF事务嵌套

ef+Npoi导出百万行excel之踩坑记

轻松把玩HttpClient之封装HttpClient工具类(现有网上分享中的最强大的工具类)