首页 > 其他分享 >EF的通用类

EF的通用类

时间:2024-04-30 16:15:28浏览次数:23  
标签:return EF dbEx ex Error 通用 Expression public

MSSql 数据库 数据层 父类
增删改查:

   /// <summary>
    /// MSSql 数据库 数据层 父类
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class BaseDAL<T> where T : class,new()
    {
        /// <summary>
        /// EF 上下文对象
        /// </summary>
        DbContext db = new DBContextFactory().GetDbContext();
#region 1.0 新增实体,返回受影响的行数 +  int Add(T model)
        /// <summary>
        /// 1.0 新增实体,返回受影响的行数
        /// </summary>
        /// <param name="model"></param>
        /// <returns>返回受影响的行数</returns>
        public int Add(T model)
        {
            db.Set<T>().Add(model);
            //保存成功后,会将自增的id设置给model的主键属性,并返回受影响的行数。
            return db.SaveChanges();
        }
        #endregion

        #region 1.1 新增实体,返回对应的实体对象 + T AddReturnModel(T model)
        /// <summary>
        /// 1.1 新增实体,返回对应的实体对象
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public T AddReturnModel(T model)
        {
            db.Set<T>().Add(model);
            db.SaveChanges();
            return model;
        }
        #endregion
#region 2.0 根据id删除 +  int Del(T model)
        /// <summary>
        /// 2.0 根据id删除
        /// </summary>
        /// <param name="model">必须包含要删除id的对象</param>
        /// <returns></returns>
        public int Del(T model)
        {
            db.Set<T>().Attach(model);
            db.Set<T>().Remove(model);
            return db.SaveChanges();
        }
        #endregion

        #region 2.1 根据条件删除 + int DelBy(Expression<Func<T, bool>> delWhere)
        /// <summary>
        /// 2.1 根据条件删除
        /// </summary>
        /// <param name="delWhere"></param>
        /// <returns>返回受影响的行数</returns>
        public int DelBy(Expression<Func<T, bool>> delWhere)
        {
            //2.1.1 查询要删除的数据
            List<T> listDeleting = db.Set<T>().Where(delWhere).ToList();
            //2.1.2 将要删除的数据 用删除方法添加到 EF 容器中
            listDeleting.ForEach(u =>
                {
                    db.Set<T>().Attach(u);  //先附加到EF 容器
                    db.Set<T>().Remove(u); //标识为删除状态
                });
            //2.1.3 一次性生成sql语句 到数据库执行删除
            return db.SaveChanges();
        }
        #endregion
#region 3.0 修改实体 +  int Modify(T model)
        /// <summary>
        /// 修改实体
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int Modify(T model)
        {
            DbEntityEntry entry = db.Entry<T>(model);
            entry.State = EntityState.Modified;
            return db.SaveChanges();
        }
        #endregion

        #region 3.1 修改实体,可修改指定属性 + int Modify(T model, params string[] propertyNames)
        /// <summary>
        /// 3.1 修改实体,可修改指定属性
        /// </summary>
        /// <param name="model"></param>
        /// <param name="propertyName"></param>
        /// <returns></returns>
        public int Modify(T model, params string[] propertyNames)
        {
            //3.1.1 将对象添加到EF中
            DbEntityEntry entry = db.Entry<T>(model);
            //3.1.2 先设置对象的包装状态为 Unchanged
            entry.State = EntityState.Unchanged;
            //3.1.3 循环被修改的属性名数组
            foreach (string propertyName in propertyNames)
            {
                //将每个被修改的属性的状态设置为已修改状态;这样在后面生成的修改语句时,就只为标识为已修改的属性更新
                entry.Property(propertyName).IsModified = true;
            }
            return db.SaveChanges();
        }
        #endregion

        #region 3.2 批量修改 + int ModifyBy(T model, Expression<Func<T, bool>> whereLambda, params string[] modifiedPropertyNames)
        /// <summary>
        /// 3.2 批量修改
        /// </summary>
        /// <param name="model"></param>
        /// <param name="whereLambda"></param>
        /// <param name="modifiedPropertyNames"></param>
        /// <returns></returns>
        public int ModifyBy(T model, Expression<Func<T, bool>> whereLambda, params string[] modifiedPropertyNames)
        {
            //3.2.1 查询要修改的数据
            List<T> listModifing = db.Set<T>().Where(whereLambda).ToList();
            //3.2.2 获取实体类类型对象
            Type t = typeof(T);
            //3.2.3 获取实体类所有的公共属性
            List<PropertyInfo> propertyInfos = t.GetProperties(BindingFlags.Instance | BindingFlags.Public).ToList();
            //3.2.4 创建实体属性字典集合
            Dictionary<string, PropertyInfo> dicPropertys = new Dictionary<string, PropertyInfo>();
            //3.2.5 将实体属性中要修改的属性名 添加到字典集合中  键:属性名  值:属性对象
            propertyInfos.ForEach(p =>
                {
                    if (modifiedPropertyNames.Contains(p.Name))
                    {
                        dicPropertys.Add(p.Name, p);
                    }
                });
            //3.2.6 循环要修改的属性名
            foreach (string propertyName in modifiedPropertyNames)
            {
                //判断要修改的属性名是否在实体类的属性集合中存在
                if (dicPropertys.ContainsKey(propertyName))
                {
                    //如果存在,则取出要修改的属性对象
                    PropertyInfo proInfo = dicPropertys[propertyName];
                    //取出要修改的值
                    object newValue = proInfo.GetValue(model, null);
                    //批量设置要修改对象的属性
                    foreach (T item in listModifing)
                    {
                        //为要修改的对象的要修改的属性设置新的值
                        proInfo.SetValue(item, newValue, null);
                    }
                }
            }
            //一次性生成sql语句 到数据库执行
            return db.SaveChanges();
        }
        #endregion
#region 4.0 根据条件查询单个model + T GetModel(Expression<Func<T, bool>> whereLambda)
        /// <summary>
        /// 4.0 根据条件查询单个model
        /// </summary>
        /// <param name="whereLambda"></param>
        /// <returns></returns>
        public T GetModel(Expression<Func<T, bool>> whereLambda)
        {
            return db.Set<T>().Where(whereLambda).AsNoTracking().FirstOrDefault();
        }
        #endregion

        #region 4.1 根据条件查询单个model并排序  +  T GetModel<TKey>(Expression<Func<T, bool>> whereLambda, Expression<Func<T, TKey>> orderLambda, bool isAsc = true)
        /// <summary>
        /// 4.1 根据条件查询单个model并排序
        /// </summary>
        /// <typeparam name="TKey"></typeparam>
        /// <param name="whereLambda"></param>
        /// <param name="orderLambda"></param>
        /// <param name="isAsc"></param>
        /// <returns></returns>
        public T GetModel<TKey>(Expression<Func<T, bool>> whereLambda, Expression<Func<T, TKey>> orderLambda, bool isAsc = true)
        {
            if (isAsc)
            {
                return db.Set<T>().Where(whereLambda).OrderBy(orderLambda).AsNoTracking().FirstOrDefault();
            }
            else
            {
                return db.Set<T>().Where(whereLambda).OrderByDescending(orderLambda).AsNoTracking().FirstOrDefault();
            }
        }
        #endregion
 #region  5.0 根据条件查询 + List<T> GetListBy(Expression<Func<T, bool>> whereLambda)
        /// <summary>
        /// 5.0 根据条件查询
        /// </summary>
        /// <param name="whereLambda"></param>
        /// <returns></returns>
        public List<T> GetListBy(Expression<Func<T, bool>> whereLambda)
        {
            return db.Set<T>().Where(whereLambda).AsNoTracking().ToList();
        }
        #endregion

        #region 5.1 根据条件查询,并排序 +  List<T> GetListBy<TKey>(Expression<Func<T, bool>> whereLambda, Expression<Func<T, TKey>> orderLambda, bool isAsc = true)
        /// <summary>
        /// 5.1 根据条件查询,并排序
        /// </summary>
        /// <typeparam name="TKey"></typeparam>
        /// <param name="whereLambda"></param>
        /// <param name="orderLambda"></param>
        /// <param name="isAsc"></param>
        /// <returns></returns>
        public List<T> GetListBy<TKey>(Expression<Func<T, bool>> whereLambda, Expression<Func<T, TKey>> orderLambda, bool isAsc = true)
        {
            if (isAsc)
            {
                return db.Set<T>().Where(whereLambda).OrderBy(orderLambda).AsNoTracking().ToList();
            }
            else
            {
                return db.Set<T>().Where(whereLambda).OrderByDescending(orderLambda).AsNoTracking().ToList();
            }
        }
        #endregion

        #region 5.2 根据条件查询Top多少个,并排序 + List<T> GetListBy<TKey>(int top, Expression<Func<T, bool>> whereLambda, Expression<Func<T, TKey>> orderLambda, bool isAsc = true)
        /// <summary>
        /// 5.2 根据条件查询Top多少个,并排序
        /// </summary>
        /// <typeparam name="TKey"></typeparam>
        /// <param name="top"></param>
        /// <param name="whereLambda"></param>
        /// <param name="orderLambda"></param>
        /// <param name="isAsc"></param>
        /// <returns></returns>
        public List<T> GetListBy<TKey>(int top, Expression<Func<T, bool>> whereLambda, Expression<Func<T, TKey>> orderLambda, bool isAsc = true)
        {
            if (isAsc)
            {
                return db.Set<T>().Where(whereLambda).OrderBy(orderLambda).Take(top).AsNoTracking().ToList();
            }
            else
            {
                return db.Set<T>().Where(whereLambda).OrderByDescending(orderLambda).Take(top).AsNoTracking().ToList();
            }
        }
        #endregion

#region  5.3 根据条件排序查询  双排序 + List<T> GetListBy<TKey1, TKey2>(Expression<Func<T, bool>> whereLambda, Expression<Func<T, TKey1>> orderLambda1, Expression<Func<T, TKey2>> orderLambda2, bool isAsc1 = true, bool isAsc2 = true)
        /// <summary>
        /// 5.3 根据条件排序查询  双排序
        /// </summary>
        /// <typeparam name="TKey1"></typeparam>
        /// <typeparam name="TKey2"></typeparam>
        /// <param name="whereLambda"></param>
        /// <param name="orderLambda1"></param>
        /// <param name="orderLambda2"></param>
        /// <param name="isAsc1"></param>
        /// <param name="isAsc2"></param>
        /// <returns></returns>
        public List<T> GetListBy<TKey1, TKey2>(Expression<Func<T, bool>> whereLambda, Expression<Func<T, TKey1>> orderLambda1, Expression<Func<T, TKey2>> orderLambda2, bool isAsc1 = true, bool isAsc2 = true)
        {
            if (isAsc1)
            {
                if (isAsc2)
                {
                    return db.Set<T>().Where(whereLambda).OrderBy(orderLambda1).ThenBy(orderLambda2).AsNoTracking().ToList();
                }
                else
                {
                    return db.Set<T>().Where(whereLambda).OrderBy(orderLambda1).ThenByDescending(orderLambda2).AsNoTracking().ToList();
                }
            }
            else
            {
                if (isAsc2)
                {
                    return db.Set<T>().Where(whereLambda).OrderByDescending(orderLambda1).ThenBy(orderLambda2).AsNoTracking().ToList();
                }
                else
                {
                    return db.Set<T>().Where(whereLambda).OrderByDescending(orderLambda1).ThenByDescending(orderLambda2).AsNoTracking().ToList();
                }
            }
        } 
        #endregion

#region 5.3 根据条件排序查询Top个数  双排序 + List<T> GetListBy<TKey1, TKey2>(int top, Expression<Func<T, bool>> whereLambda, System.Linq.Expressions.Expression<Func<T, TKey1>> orderLambda1, Expression<Func<T, TKey2>> orderLambda2, bool isAsc1 = true, bool isAsc2 = true)
        /// <summary>
        ///  5.3 根据条件排序查询Top个数  双排序
        /// </summary>
        /// <typeparam name="TKey1"></typeparam>
        /// <typeparam name="TKey2"></typeparam>
        /// <param name="top"></param>
        /// <param name="whereLambda"></param>
        /// <param name="orderLambda1"></param>
        /// <param name="orderLambda2"></param>
        /// <param name="isAsc1"></param>
        /// <param name="isAsc2"></param>
        /// <returns></returns>
        public List<T> GetListBy<TKey1, TKey2>(int top, Expression<Func<T, bool>> whereLambda, Expression<Func<T, TKey1>> orderLambda1, Expression<Func<T, TKey2>> orderLambda2, bool isAsc1 = true, bool isAsc2 = true)
        {
            if (isAsc1)
            {
                if (isAsc2)
                {
                    return db.Set<T>().Where(whereLambda).OrderBy(orderLambda1).ThenBy(orderLambda2).Take(top).AsNoTracking().ToList();
                }
                else
                {
                    return db.Set<T>().Where(whereLambda).OrderBy(orderLambda1).ThenByDescending(orderLambda2).Take(top).AsNoTracking().ToList();
                }
            }
            else
            {
                if (isAsc2)
                {
                    return db.Set<T>().Where(whereLambda).OrderByDescending(orderLambda1).ThenBy(orderLambda2).Take(top).AsNoTracking().ToList();
                }
                else
                {
                    return db.Set<T>().Where(whereLambda).OrderByDescending(orderLambda1).ThenByDescending(orderLambda2).Take(top).AsNoTracking().ToList();
                }
            }
        } 
        #endregion
#region 6.0 分页查询 + List<T> GetPagedList<TKey>
        /// <summary>
        /// 分页查询 + List<T> GetPagedList
        /// </summary>
        /// <typeparam name="TKey"></typeparam>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">页容量</param>
        /// <param name="whereLambda">条件 lambda表达式</param>
        /// <param name="orderBy">排序 lambda表达式</param>
        /// <returns></returns>
        public List<T> GetPagedList<TKey>(int pageIndex, int pageSize, Expression<Func<T, bool>> whereLambda, Expression<Func<T, TKey>> orderByLambda, bool isAsc = true)
        {
            // 分页 一定注意: Skip 之前一定要 OrderBy
            if (isAsc)
            {
                return db.Set<T>().Where(whereLambda).OrderBy(orderByLambda).Skip((pageIndex - 1) * pageSize).Take(pageSize).AsNoTracking().ToList();
            }
            else
            {
                return db.Set<T>().Where(whereLambda).OrderByDescending(orderByLambda).Skip((pageIndex - 1) * pageSize).Take(pageSize).AsNoTracking().ToList();
            }
        }
        #endregion

        #region 6.1分页查询 带输出 +List<T> GetPagedList<TKey>
        /// <summary>
        /// 分页查询 带输出
        /// </summary>
        /// <typeparam name="TKey"></typeparam>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowCount"></param>
        /// <param name="whereLambda"></param>
        /// <param name="orderBy"></param>
        /// <param name="isAsc"></param>
        /// <returns></returns>
        public List<T> GetPagedList<TKey>(int pageIndex, int pageSize, ref int rowCount, Expression<Func<T, bool>> whereLambda, Expression<Func<T, TKey>> orderByLambda, bool isAsc = true)
        {
            rowCount = db.Set<T>().Where(whereLambda).Count();
            if (isAsc)
            {
                return db.Set<T>().OrderBy(orderByLambda).Where(whereLambda).Skip((pageIndex - 1) * pageSize).Take(pageSize).AsNoTracking().ToList();
            }
            else
            {
                return db.Set<T>().OrderByDescending(orderByLambda).Where(whereLambda).Skip((pageIndex - 1) * pageSize).Take(pageSize).AsNoTracking().ToList();
            }
        }
        #endregion

        #region 6.2 分页查询 带输出 并支持双字段排序
        /// <summary>
        /// 分页查询 带输出 并支持双字段排序
        /// </summary>
        /// <typeparam name="TKey"></typeparam>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowCount"></param>
        /// <param name="whereLambda"></param>
        /// <param name="orderByLambda1"></param>
        /// <param name="orderByLambda2"></param>
        /// <param name="isAsc1"></param>
        /// <param name="isAsc2"></param>
        /// <returns></returns>
        public List<T> GetPagedList<TKey1, TKey2>(int pageIndex, int pageSize, ref int rowCount, Expression<Func<T, bool>> whereLambda, Expression<Func<T, TKey1>> orderByLambda1, Expression<Func<T, TKey2>> orderByLambda2, bool isAsc1 = true, bool isAsc2 = true)
        {
            rowCount = db.Set<T>().Where(whereLambda).Count();
            if (isAsc1)
            {
                if (isAsc2)
                {
                    return db.Set<T>().OrderBy(orderByLambda1).ThenBy(orderByLambda2).Where(whereLambda).Skip((pageIndex - 1) * pageSize).Take(pageSize).AsNoTracking().ToList();
                }
                else
                {
                    return db.Set<T>().OrderBy(orderByLambda1).ThenByDescending(orderByLambda2).Where(whereLambda).Skip((pageIndex - 1) * pageSize).Take(pageSize).AsNoTracking().ToList();
                }
            }
            else
            {
                if (isAsc2)
                {
                    return db.Set<T>().OrderByDescending(orderByLambda1).ThenBy(orderByLambda2).Where(whereLambda).Skip((pageIndex - 1) * pageSize).Take(pageSize).AsNoTracking().ToList();
                }
                else
                {
                    return db.Set<T>().OrderByDescending(orderByLambda1).ThenByDescending(orderByLambda2).Where(whereLambda).Skip((pageIndex - 1) * pageSize).Take(pageSize).AsNoTracking().ToList();
                }
            }
        }
        #endregion
    }
}

封装类

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

    }

}

 

标签:return,EF,dbEx,ex,Error,通用,Expression,public
From: https://www.cnblogs.com/liuqifeng/p/18168186

相关文章

  • 使用EF框架的优化(四)
    EF容易忽略的优化点-能转换成SQL执行的,不要在内存中执行,否则,性能很差!只选择某列或某些列有些时候,在C#里写LINQ虽然看着舒服,但性能不一定好,所以有必要做一些调整。比如这种情况:我需要知道一篇文章的点击数,仅此而已,我可能会写:context.Post.FirstOrDefault(p=>p.Id==postId).......
  • 好用的自动同步软件:FreeFileSync
    最近研究怎么能够将文件从电脑上自动备份到移动硬盘,发现了很多人都在安利的FreeFileSync(官网:FreeFileSync )FreeFileSync​freefilesync.org/这是一个免费软件,在各个系统中都有提供安装包。软件安装过程非常简单,目前我将其直接安装到了C盘,安装好后即可看到两个软件:绿色的FreeFil......
  • react中什么使用定义变量,需要使用useRef,什么时候直接定义即可?
    在React中,决定使用useState、useRef或是直接定义变量,主要取决于你希望变量如何与组件的渲染周期互动以及是否需要持久化某些值。直接定义变量场景:如果你只是需要一个在函数内部临时存储数据的变量,而且这个变量的值不需要在组件重新渲染时保持不变,或者它并不直接影响UI的渲染逻......
  • react中如何区分什么场景下应该使用useEffect,什么场景下应该使用发布订阅模式,进行通信
    在React中,useEffect和发布订阅模式(Pub/Sub)解决的是不同层面的问题,因此它们的使用场景也有所不同。useEffect的使用场景数据获取:当组件挂载后需要从服务器获取数据时,可以使用useEffect。同时,当依赖项发生变化时,它也能帮助重新获取数据。副作用处理:任何需要在渲染之外进行的......
  • Go语言系列——Go协程、信道(channel)、缓冲信道和工作池、Select、Mutex、结构体取代类
    文章目录21-Go协程Go协程是什么?Go协程相比于线程的优势如何启动一个Go协程?启动多个Go协程22-信道(channel)什么是信道?信道的声明通过信道进行发送和接收发送与接收默认是阻塞的信道的代码示例信道的另一个示例死锁单向信道关闭信道和使用forrange遍历信道23-缓冲信......
  • spring-web-mvc项目运行报错:java.lang.NoClassDefFoundError: org/apache/catalina/We
    使用idea运行spring-web-mvc项目时,报错如下:错误:无法初始化主类com.itranswarp.learnjava1.AppConfig原因:java.lang.NoClassDefFoundError:org/apache/catalina/WebResourceRoot 首先,保证当前项目在独立的项目中打开,不要在多个项目中运行。导入Maven工程要选择:File......
  • Reflexion: Language Agents with Verbal Reinforcement Learning
    发表时间:2023(NeurIPS2023)文章要点:文章提出Reflexion框架,通过交互的方式获得反馈,并变成细致的语言feedback的形式作为下一轮的prompt,以此强化languageagents的能力,同时避免了更新大模型的参数。这样的好处有1)轻量,不需要finetuneLLM,2)feedback相比一个reward信号更加细致,3)充分......
  • 使用EF框架的优化(三)-大量数据查询
    在C#中使用EF查询数据库数据,将结果直接转换为List是一个常见的做法。这样做的好处是方便快捷,可以方便地对结果集进行操作和遍历。但是也存在一些问题:1.性能问题:将查询结果直接转换为List会加载整个结果集到内存中,如果查询结果较大,可能会导致性能问题和内存占用过高。2.内存管......
  • 领域、子域、核心域、通用域和支撑域:傻傻分不清?
    https://zq99299.github.io/note-book2/ddd/01/02.htmlDDD的知识体系提出了很多的名词,像:领域、子域、核心域、通用域、支撑域、限界上下文、聚合、聚合根、实体、值对象等等,非常多。这些名词,都是关键概念,但它们实在有些晦涩难懂,可能导致你还没开始实践DDD就打起了退堂鼓。因此......
  • NoClassDefFoundError: org/slf4j/impl/StaticLoggerBinder
    NoClassDefFoundError:org/slf4j/impl/StaticLoggerBinderSpringBoot2.7.xxxlogback1.3.xxx实际上原因是logback-classic从v1.3.0中删除了org/slf4j/impl/StaticLoggerBinder,而spring-boot2.x只支持logback到v1.2.x(目前是1.2.12)。以下是相关问题:https://github.com/sprin......