自己封装了一个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

    }

}

..求大神指点一下..哪里有问题..我在改改..

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏everhad

消息处理管道

TODO: 待写 消息处理管道 一个App看作是系统,外部输入消息需要经过一系列处理,涉及不同接收者。消息处理的跟踪(Trace)和结果的保存。 比如设计一个...

1846
来自专栏行者常至

数据库连接池简单连接

模型      -----     Model 视图      -----     View 控制器  -----     Controller

753
来自专栏IMWeb前端团队

Common Pitfalls to Avoid when using HTML5 Application Cache

本文作者:IMWeb 黎腾 原文出处:IMWeb社区 未经同意,禁止转载 Application Cache, also known as AppCa...

1767
来自专栏cmazxiaoma的架构师之路

Java开发技术大杂烩(三)之电商项目优化、rabbitmq、Git、OSI、VIM、Intellj IDEA、HTTP、JS、Java

2417
来自专栏平凡文摘

Spring Boot 内嵌容器 Tomcat / Undertow / Jetty 优雅停机实现

1532
来自专栏Java与Android技术栈

RxJava的Single、Completable以及Maybe

通常情况下,如果我们想要使用 RxJava 首先会想到的是使用Observable,如果要考虑到Backpressure的情况,在 RxJava2.x 时代我们...

772
来自专栏分布式系统进阶

Kafka集群Metadata管理Kafka源码分析-汇总

可以看到是调用了ReplicaManager.maybeUpdateMetadataCache方法, 里面又会调用到MetadataCache.updateCa...

572
来自专栏C# 编程

C# 读取XML文件示例

有关XML文件编写规范,请参考:http://www.w3school.com.cn/xml/index.asp XML内容如下(文件名为:Informatio...

2060
来自专栏james大数据架构

Excel导入导出数据库01

主要分为两部份 1.Excel操作类 1 引入 2 using System.Data.OleDb; 3 using System.IO; 4 ...

20010
来自专栏听雨堂

异步方式访问网页

采用BackgroundWorker,在后台执行程序,往往比开新线程更简单和更加安全。 简单的使用方法 System.ComponentModel.Backgr...

1809

扫码关注云+社区