netCore封装efcore仓储模式

netCore封装efcore仓储模式

参考:三层框架项目搭建教程

安装依赖包

Install-Package MySql.Data.EntityFrameworkCore -Pre
Install-Package Pomelo.EntityFrameworkCore.MySql
Install-Package Microsoft.EntityFrameworkCore.Tools
Install-Package Microsoft.VisualStudio.Web.CodeGeneration.Design

管理器控制台

输入以下代码

Scaffold-DbContext "server=localhost;userid=root;pwd=1;port=3306;database=syerp;sslmode=none;" Pomelo.EntityFrameworkCore.MySql -OutputDir Models -Force

自动生成所有类模型文件,数据库上下文自动创建好了

-OutputDir  实体文件所存放的文件目录
-ContextDir DbContext文件存放的目录
-Context  DbContext文件名
-Schemas  需要生成实体数据的数据表所在的模式
-Tables  需要生成实体数据的数据表的集合
-DataAnnotations
-UseDatabaseNames  直接使用数据库中的表名和列名(某些版本不支持)
-Force   强制执行,重写已经存在的实体文件

链接: asp.net core3.1 实战开发(EF+Mysql 从数据库生成实体类到项目)

封装仓储模式

IRepositorys接口

using System.Data;
using System.Data.Common;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace Snblog.IRepository.IRepository
{
    public interface IRepositorys<T> : IDisposable where T : class
    {
        # region 显式开启数据上下文事务
        /// <summary>
        /// 显式开启数据上下文事务
        /// </summary>
        /// <param name="isolationLevel">指定连接的事务锁定行为</param>
        void BeginTransaction(IsolationLevel isolationLevel = IsolationLevel.Unspecified);
        # endregion

        # region 提交事务的更改
        /// <summary>
        /// 提交事务的更改
        /// </summary>
        void Commit();
        # endregion

        # region 显式回滚事务,仅在显式开启事务后有用
        /// <summary>
        /// 显式回滚事务,仅在显式开启事务后有用
        /// </summary>
        void Rollback();
        #endregion

        #region 提交当前单元操作的更改
        /// <summary>
        /// 提交当前单元操作的更改
        /// </summary>
        int SaveChanges();
        #endregion

        #region 提交当前单元操作的更改
        /// <summary>
        /// 提交当前单元操作的更改
        /// </summary>
        /// <returns></returns>
        Task<int> SaveChangesAsync();
        #endregion

        #region 获取 当前实体类型的查询数据集,数据将使用不跟踪变化的方式来查询,当数据用于展现时,推荐使用此数据集,如果用于新增,更新,删除时,请使用<see cref="TrackEntities"/>数据集
        /// <summary>
        /// 获取 当前实体类型的查询数据集,数据将使用不跟踪变化的方式来查询,当数据用于展现时,推荐使用此数据集,如果用于新增,更新,删除时,请使用<see cref="TrackEntities"/>数据集
        /// </summary>
        IQueryable<T> Entities { get; }
        #endregion

        #region 获取 当前实体类型的查询数据集,当数据用于新增,更新,删除时,使用此数据集,如果数据用于展现,推荐使用<see cref="Entities"/>数据集
        /// <summary>
        /// 获取 当前实体类型的查询数据集,当数据用于新增,更新,删除时,使用此数据集,如果数据用于展现,推荐使用<see cref="Entities"/>数据集
        /// </summary>
        IQueryable<T> TrackEntities { get; }
        #endregion

        #region 插入 - 通过实体对象添加
        /// <summary>
        /// 插入 - 通过实体对象添加
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <param name="isSave">是否执行</param>
        /// /// <returns></returns>
        T Add(T entity, bool isSave = true);
        Task<T> AddAsync(T entity, bool isSave = true);
        /// <summary>
        /// 批量插入 - 通过实体对象集合添加
        /// </summary>
        /// <param name="entitys">实体对象集合</param>
        /// <param name="isSave">是否执行</param>
        void AddRange(IEnumerable<T> entitys, bool isSave = true);
        bool Insert(T entity, bool isSaveChange);
        Task<bool> InsertAsync(T entity, bool isSaveChange);
        bool Insert(List<T> entitys, bool isSaveChange = true);
        Task<bool> InsertAsync(List<T> entitys, bool isSaveChange);

        #endregion

        #region 删除(删除之前需要查询)

        bool Delete(List<T> entitys, bool isSaveChange);
        Task<bool> DeleteAsync(T entity, bool isSaveChange);
        Task<bool> DeleteAsync(List<T> entitys, bool isSaveChange = true);
        /// <summary>
        /// 删除 - 通过实体对象删除
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <param name="isSave">是否执行</param>
        void Delete(T entity, bool isSave = true);

        /// <summary>
        /// 批量删除 - 通过实体对象集合删除
        /// </summary>
        /// <param name="entitys">实体对象集合</param>
        /// <param name="isSave">是否执行</param>
        void Delete(bool isSave = false, params T[] entitys);

        /// <summary>
        /// 删除 - 通过主键ID删除
        /// </summary>
        /// <param name="id">主键ID</param>
        Task<int> DelAsync(object id);
        /// <summary>
        /// 批量删除 - 通过条件删除
        /// </summary>
        /// <param name="where">过滤条件</param>
        /// <param name="isSave">是否执行</param>
        void Delete(Expression<Func<T, bool>> @where, bool isSave = true);
        #endregion

        #region 修改数据
        bool Update(T entity, bool isSaveChange, List<string> updatePropertyList);
        Task<bool> UpdateAsync(T entity, bool isSaveChange, List<string> updatePropertyList);
        /// <summary>
        /// 更新单个字段
        /// </summary>
        /// <param name="entity">实体类</param>
        /// <param name="isSaveChange">是否更新</param>
        /// <param name="updatePropert">更新的字段</param>
        /// <returns></returns>
        Task<bool> UpdateAsync1(T entity, bool isSaveChange, string updatePropert);
        bool Update(List<T> entitys, bool isSaveChange);
        Task<bool> UpdateAsync(List<T> entitys, bool isSaveChange);

        /// <summary>
        /// 修改 - 通过实体对象修改
        /// </summary>
        /// <param name="entity">实体对象</param>
        Task<int> UpdateAsync(T entity);
        int Update(T entity);
        /// <summary>
        /// 批量修改 - 通过实体对象集合修改
        /// </summary>
        /// <param name="entitys">实体对象集合</param>
        void Update(params T[] entitys);
        #endregion

        #region 查找数据

        /// <summary>
        /// 是否满足条件
        /// </summary>
        /// <param name="where">过滤条件</param>
        /// <returns></returns>
        bool Any(Expression<Func<T, bool>> @where);

        /// <summary>
        /// 返回总条数
        /// </summary>
        /// <returns></returns>
        int Count();
        Task<int> CountAsync();
        /// <summary>
        /// 返回总条数 - 通过条件过滤
        /// </summary>
        /// <param name="where">过滤条件</param>
        /// <returns></returns>
        int Count(Expression<Func<T, bool>> @where);

        /// <summary>
        /// 返回总条数 - 通过条件过滤
        /// </summary>
        /// <param name="where"></param>
        /// <returns></returns>
        Task<int> CountAsync(Expression<Func<T, bool>> @where);
        /// <summary>
        /// 返回第一条记录
        /// </summary>
        /// <param name="where">过滤条件</param>
        /// <returns></returns>
        T FirstOrDefault(Expression<Func<T, bool>> @where);
        /// <summary>
        /// 返回第一条记录 - 通过条件过滤
        /// </summary>
        /// <typeparam name="TOrder">排序约束</typeparam>
        /// <param name="where">过滤条件</param>
        /// <param name="order">排序条件</param>
        /// <param name="isDesc">排序方式</param>
        /// <returns></returns>
        T FirstOrDefault<TOrder>(Expression<Func<T, bool>> @where, Expression<Func<T, TOrder>> order, bool isDesc = false);

        /// <summary>
        /// 去重查询
        /// </summary>
        /// <param name="where">过滤条件</param>
        /// <returns></returns>
        IQueryable<T> Distinct(Expression<Func<T, bool>> @where);


        /// <summary>
        /// 条件查询
        /// </summary>
        /// <param name="where">过滤条件</param>
        /// <returns></returns>
        IQueryable<T> Where(Expression<Func<T, bool>> @where);

        /// <summary>
        /// 条件查询
        /// </summary>
        /// <param name="where">过滤条件</param>
        /// <returns></returns>
        Task<IQueryable<T>> WhereAsync(Expression<Func<T, bool>> @where);

        /// <summary>
        /// 条件查询 - 支持排序
        /// </summary>
        /// <typeparam name="TOrder">排序约束</typeparam>
        /// <param name="where">过滤条件</param>
        /// <param name="order">排序条件</param>
        /// <param name="isDesc">排序方式</param>
        /// <returns></returns>
        IQueryable<T> Where<TOrder>(Expression<Func<T, bool>> @where, Expression<Func<T, TOrder>> order, bool isDesc = false);


        /// <summary>
        /// 条件分页查询 - 支持排序
        /// </summary>
        /// <typeparam name="TOrder">排序约束</typeparam>
        /// <param name="where">过滤条件</param>
        /// <param name="order">排序条件</param>
        /// <param name="pageIndex">当前页码</param>
        /// <param name="pageSize">每页记录条数</param>
        /// <param name="count">返回总条数</param>
        /// <param name="isDesc">是否倒序</param>
        IEnumerable<T> WherePage<TOrder>(Func<T, bool> @where, Func<T, TOrder> order, int pageIndex, int pageSize, out int count, bool isDesc);
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="TOrder">排序约束</typeparam>
        /// <param name="where">过滤条件</param>
        /// <param name="order">排序条件</param>
        /// <param name="pageIndex">当前页码</param>
        /// <param name="pageSize">每页记录条数</param>
        /// <param name="isDesc">是否倒序</param>
        /// <returns></returns>

        Task<IEnumerable<T>> WherePageAsync<TOrder>(Func<T, bool> @where, Func<T, TOrder> order, int pageIndex, int pageSize, bool isDesc);

        /// <summary>
        /// 条件分页查询 - 支持排序
        /// </summary>
        /// <typeparam name="TOrder">排序约束</typeparam>
        /// <param name="where">过滤条件</param>
        /// <param name="order">排序条件</param>
        /// <param name="pageIndex">当前页码</param>
        /// <param name="pageSize">每页记录条数</param>
        /// <param name="count">返回总条数</param>
        /// <param name="isDesc">是否倒序</param>
        /// <returns></returns>
        IEnumerable<T> Where<TOrder>(Func<T, bool> @where, Func<T, TOrder> order, int pageIndex, int pageSize, out int count, bool isDesc = false);

        /// <summary>
        /// 条件分页查询 - 支持排序 - 支持Select导航属性查询
        /// </summary>
        /// <typeparam name="TOrder">排序约束</typeparam>
        /// <param name="where">过滤条件</param>
        /// <param name="order">排序条件</param>
        /// <param name="pageIndex">当前页码</param>
        /// <param name="pageSize">每页记录条数</param>
        /// <param name="count">返回总条数</param>
        /// <param name="isDesc">是否倒序</param>
        /// <returns></returns>
        IQueryable<T> Where<TOrder>(Expression<Func<T, bool>> @where, Expression<Func<T, TOrder>> order, int pageIndex, int pageSize, out int count, bool isDesc = false);

        /// <summary>
        /// 获取所有数据
        /// </summary>
        /// <returns></returns>
        IQueryable<T> GetAll();

        /// <summary>
        /// 查询所有
        /// </summary>
        /// <returns></returns>
        Task<List<T>> GetAllAsync();

        /// <summary>
        /// 获取所有数据 - 支持排序
        /// </summary>
        /// <typeparam name="TOrder">排序约束</typeparam>
        /// <param name="order">排序条件</param>
        /// <param name="isDesc">排序方式</param>
        /// <returns></returns>
        IQueryable<T> GetAll<TOrder>(Expression<Func<T, TOrder>> order, bool isDesc = false);

        /// <summary>
        /// 根据ID查询
        /// </summary>
        /// <typeparam name="TType">字段类型</typeparam>
        /// <param name="id">主键ID</param>
        /// <returns></returns>
        T GetById<TType>(TType id);

        /// <summary>
        /// 根据ID查询
        /// </summary>
        /// <typeparam name="TType">字段类型</typeparam>
        /// <param name="id">主键</param>
        /// <returns></returns>
        Task<T> GetByIdAsync<TType>(TType id);
        /// <summary>
        /// 获取最大值
        /// </summary>
        /// <typeparam name="TType">字段类型</typeparam>
        /// <param name="column">字段条件</param>
        /// <returns></returns>
        TType Max<TType>(Expression<Func<T, TType>> column);

        /// <summary>
        /// 获取最大值
        /// </summary>
        /// <typeparam name="TType">字段类型</typeparam>
        /// <param name="column">字段条件</param>
        /// <param name="where">过滤条件</param>
        /// <returns></returns>
        TType Max<TType>(Expression<Func<T, TType>> column, Expression<Func<T, bool>> @where);

        /// <summary>
        /// 获取最小值
        /// </summary>
        /// <typeparam name="TType">字段类型</typeparam>
        /// <param name="column">字段条件</param>
        /// <returns></returns>
        TType Min<TType>(Expression<Func<T, TType>> column);

        /// <summary>
        /// 获取最小值
        /// </summary>
        /// <typeparam name="TType">字段类型</typeparam>
        /// <param name="column">字段条件</param>
        /// <param name="where">过滤条件</param>
        /// <returns></returns>
        TType Min<TType>(Expression<Func<T, TType>> column, Expression<Func<T, bool>> @where);

        /// <summary>
        /// 获取总数
        /// </summary>
        /// <typeparam name="TType">字段类型</typeparam>
        /// <param name="selector">字段条件</param>
        /// <param name="where">过滤条件</param>
        /// <returns></returns>
        TType Sum<TType>(Expression<Func<T, TType>> selector, Expression<Func<T, bool>> @where) where TType : new();
        #endregion

        #region 执行Sql语句
#pragma warning disable CS0693 // 类型参数与外部类型中的类型参数同名
        void BulkInsert<T>(List<T> entities);
#pragma warning restore CS0693 // 类型参数与外部类型中的类型参数同名
        //int ExecuteSql(string sql);
        //Task<int> ExecuteSqlAsync(string sql);
        //int ExecuteSql(string sql, List<DbParameter> spList);
        //Task<int> ExecuteSqlAsync(string sql, List<DbParameter> spList);
        DataTable GetDataTableWithSql(string sql);
        DataTable GetDataTableWithSql(string sql, List<DbParameter> spList);
        #endregion
    }
}

Repositorys类

CRUD功能的封装

namespace Snblog.Repository.Repository
{
    // Repository.cs仓储类,它是一个泛型类,并且拥有一个带有参数的构造方法,通过构造方法获得当前DbContext上下文对象,
    //泛型类为指定Model类型,通过DbContext.Set<T>()方法最终得到相应的DbSet<T>对象来操作工作单元。
    //实现了CRUD基本功能的封装
    public class Repositorys<T> : IRepositorys<T> where T : class
    {
        private readonly snblogContext _dbContext;
        private readonly DbSet<T> _dbSet;
        private readonly string _connStr;

        public Repositorys(IConcardContext mydbcontext)
        {
            _dbContext = mydbcontext as snblogContext;
            if (_dbContext == null)
            {
                return;
            }

            _dbSet = _dbContext.Set<T>();
            _connStr = _dbContext.Database.GetDbConnection().ConnectionString;
        }

        public void BeginTransaction(IsolationLevel isolationLevel = IsolationLevel.Unspecified)
        {
            if (_dbContext.Database.CurrentTransaction == null)
            {
                _dbContext.Database.BeginTransaction(isolationLevel);
            }
        }

        public void Commit()
        {
            var transaction = this._dbContext.Database.CurrentTransaction;
            if (transaction != null)
            {
                try
                {
                    transaction.Commit();
                }
                catch (Exception)
                {
                    transaction.Rollback();
                    throw;
                }
            }
        }

        public void Rollback()
        {
            _dbContext.Database.CurrentTransaction?.Rollback();
        }

        public int SaveChanges()
        {
            return _dbContext.SaveChanges();
        }
        public async Task<int> SaveChangesAsync()
        {
            return await _dbContext.SaveChangesAsync();
        }


        public IQueryable<T> Entities
        {
            get { return _dbSet.AsNoTracking(); }
        }

        public IQueryable<T> TrackEntities
        {
            get { return _dbSet; }
        }

        public T Add(T entity, bool isSave = true)
        {

            _dbSet.Add(entity);
            if (isSave)
            {
                SaveChanges();
            }
            return entity;
        }

        public async Task<T> AddAsync(T entity, bool isSave = true)
        {
            await _dbSet.AddAsync(entity);
            if (isSave)
            {
                await SaveChangesAsync();
            }
            return entity;
        }

        public void AddRange(IEnumerable<T> entitys, bool isSave = true)
        {
            _dbSet.AddRange(entitys);
            if (isSave)
            {
                SaveChanges();
            }
        }

        public void Delete(T entity, bool isSave = true)
        {
            this._dbSet.Remove(entity);
            if (isSave)
            {
                this.SaveChanges();
            }
        }

        public void Delete(bool isSave = true, params T[] entitys)
        {
            this._dbSet.RemoveRange(entitys);
            if (isSave)
            {
                this.SaveChanges();
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns>-1 || 1</returns>
        public async Task<int> DelAsync(object id)
        {
            var result = await _dbSet.FindAsync(id);
            if (result == null) return -1;
            _dbSet.Remove(result);
            return  SaveChanges();
        }

        public void Delete(Expression<Func<T, bool>> @where, bool isSave = true)
        {
            T[] entitys = this._dbSet.Where(@where).ToArray();
            if (entitys.Length > 0)
            {
                this._dbSet.RemoveRange(entitys);
            }
            if (isSave)
            {
                this.SaveChanges();
            }
        }

        public async Task<int> UpdateAsync(T entity)
        {
            var en = _dbContext.Entry(entity);
            if (en.State == EntityState.Detached) en.State = EntityState.Modified;
            return await Task.Run(SaveChangesAsync);
        }

        public int Update(T entity)
        {

            var entry = _dbContext.Entry(entity);
            if (entry.State == EntityState.Detached)
            {
                entry.State = EntityState.Modified;
            }
            var da = SaveChanges();
            return da;
        }
        public void Update(params T[] entitys)
        {
            var entry = this._dbContext.Entry(entitys);
            if (entry.State == EntityState.Detached)
            {
                entry.State = EntityState.Modified;
            }
            SaveChanges();
        }

        public bool Any(Expression<Func<T, bool>> @where)
        {
            return _dbSet.AsNoTracking().Any(@where);
        }

        public int Count()
        {
            return _dbSet.AsNoTracking().Count();
        }

        public int Count(Expression<Func<T, bool>> @where)
        {
            return _dbSet.AsNoTracking().Count(@where);
        }

        public T FirstOrDefault(Expression<Func<T, bool>> @where)
        {
            return _dbSet.AsNoTracking().FirstOrDefault(@where);
        }

        public T FirstOrDefault<TOrder>(Expression<Func<T, bool>> @where, Expression<Func<T, TOrder>> order, bool isDesc = false)
        {
            if (isDesc)
            {
                return this._dbSet.AsNoTracking().OrderByDescending(order).FirstOrDefault(@where);
            }
            else
            {
                return this._dbSet.AsNoTracking().OrderBy(order).FirstOrDefault(@where);
            }
        }

        public IQueryable<T> Distinct(Expression<Func<T, bool>> @where)
        {
            return this._dbSet.AsNoTracking().Where(@where).Distinct();

        }


        public IQueryable<T> Where(Expression<Func<T, bool>> @where)
        {
            return this._dbSet.Where(@where);
        }

        public IQueryable<T> Where<TOrder>(Expression<Func<T, bool>> @where, Expression<Func<T, TOrder>> order, bool isDesc = false)
        {
            if (isDesc)
            {
                return this._dbSet.Where(@where).OrderByDescending(order);
            }
            else
            {
                return this._dbSet.Where(@where).OrderBy(order);
            }
        }


        public IEnumerable<T> WherePage<TOrder>(Func<T, bool> @where, Func<T, TOrder> order, int pageIndex, int pageSize, out int count, bool isDesc)
        {
            count = Count();
            if (isDesc)
            {

                return _dbSet.Where(@where).OrderByDescending(order).Skip((pageIndex - 1) * pageSize).Take(pageSize);
            }
            else
            {
                return this._dbSet.Where(@where).OrderBy(order).Skip((pageIndex - 1) * pageSize).Take(pageSize);
            }
        }
        public async Task<IEnumerable<T>> WherePageAsync<TOrder>(Func<T, bool> @where, Func<T, TOrder> order, int pageIndex, int pageSize, bool isDesc)
        {
            if (isDesc)
            {
                return await Task.Run(() => _dbSet.Where(@where).OrderByDescending(order).Skip((pageIndex - 1) * pageSize).Take(pageSize));
            }
            else
            {
                return await Task.Run(() => _dbSet.Where(@where).OrderBy(order).Skip((pageIndex - 1) * pageSize).Take(pageSize));
            }
        }

        public IEnumerable<T> Where<TOrder>(Func<T, bool> @where, Func<T, TOrder> order, int pageIndex, int pageSize, out int count, bool isDesc = false)
        {
            count = Count();
            if (isDesc)
            {
                return this._dbSet.Where(@where).OrderByDescending(order).Skip((pageIndex - 1) * pageSize).Take(pageSize);
            }
            else
            {
                return this._dbSet.Where(@where).OrderBy(order).Skip((pageIndex - 1) * pageSize).Take(pageSize);
            }
        }

        public IQueryable<T> Where<TOrder>(Expression<Func<T, bool>> @where, Expression<Func<T, TOrder>> order, int pageIndex, int pageSize, out int count, bool isDesc = false)
        {
            count = Count();
            if (isDesc)
            {
                return this._dbSet.Where(@where).OrderByDescending(order).Skip((pageIndex - 1) * pageSize).Take(pageSize);
            }
            else
            {
                return this._dbSet.Where(@where).OrderBy(order).Skip((pageIndex - 1) * pageSize).Take(pageSize);
            }
        }

        public IQueryable<T> GetAll()
        {
            return _dbSet.AsNoTracking();
        }

        public IQueryable<T> GetAll<TOrder>(Expression<Func<T, TOrder>> order, bool isDesc = false)
        {
            if (isDesc)
            {
                return this._dbSet.AsNoTracking().OrderByDescending(order);
            }
            else
            {
                return this._dbSet.AsNoTracking().OrderBy(order);
            }
        }

        public T GetById<TType>(TType id)
        {
            return this._dbSet.Find(id);
        }
        public async Task<T> GetByIdAsync<TType>(TType id)
        {
            return await _dbSet.FindAsync(id);
        }


        public TType Max<TType>(Expression<Func<T, TType>> column)
        {
            if (this._dbSet.AsNoTracking().Any())
            {
                return this._dbSet.AsNoTracking().Max(column);
            }
            return default;
        }

        public TType Max<TType>(Expression<Func<T, TType>> column, Expression<Func<T, bool>> @where)
        {
            if (this._dbSet.AsNoTracking().Any(@where))
            {
                return this._dbSet.AsNoTracking().Where(@where).Max(column);
            }
            return default;
        }

        public TType Min<TType>(Expression<Func<T, TType>> column)
        {
            if (this._dbSet.AsNoTracking().Any())
            {
                return this._dbSet.AsNoTracking().Min(column);
            }
            return default;
        }

        public TType Min<TType>(Expression<Func<T, TType>> column, Expression<Func<T, bool>> @where)
        {
            if (this._dbSet.AsNoTracking().Any(@where))
            {
                return this._dbSet.AsNoTracking().Where(@where).Min(column);
            }
            return default;
        }

        public TType Sum<TType>(Expression<Func<T, TType>> selector, Expression<Func<T, bool>> @where) where TType : new()
        {
            object result = 0;

            if (new TType().GetType() == typeof(decimal))
            {
                result = this._dbSet.AsNoTracking().Where(where).Sum(selector as Expression<Func<T, decimal>>);
            }
            if (new TType().GetType() == typeof(decimal?))
            {
                result = this._dbSet.AsNoTracking().Where(where).Sum(selector as Expression<Func<T, decimal?>>);
            }
            if (new TType().GetType() == typeof(double))
            {
                result = this._dbSet.AsNoTracking().Where(where).Sum(selector as Expression<Func<T, double>>);
            }
            if (new TType().GetType() == typeof(double?))
            {
                result = this._dbSet.AsNoTracking().Where(where).Sum(selector as Expression<Func<T, double?>>);
            }
            if (new TType().GetType() == typeof(float))
            {
                result = this._dbSet.AsNoTracking().Where(where).Sum(selector as Expression<Func<T, float>>);
            }
            if (new TType().GetType() == typeof(float?))
            {
                result = this._dbSet.AsNoTracking().Where(where).Sum(selector as Expression<Func<T, float?>>);
            }
            if (new TType().GetType() == typeof(int))
            {
                result = this._dbSet.AsNoTracking().Where(where).Sum(selector as Expression<Func<T, int>>);
            }
            if (new TType().GetType() == typeof(int?))
            {
                result = this._dbSet.AsNoTracking().Where(where).Sum(selector as Expression<Func<T, int?>>);
            }
            if (new TType().GetType() == typeof(long))
            {
                result = this._dbSet.AsNoTracking().Where(where).Sum(selector as Expression<Func<T, long>>);
            }
            if (new TType().GetType() == typeof(long?))
            {
                result = this._dbSet.AsNoTracking().Where(where).Sum(selector as Expression<Func<T, long?>>);
            }
            return (TType)result;
        }

        public void Dispose()
        {
            _dbContext.Dispose();
        }


        # region 插入数据

        /// <summary>
        /// 插入数据
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="isSaveChange"></param>
        /// <returns></returns>
        public bool Insert(T entity, bool isSaveChange = true)
        {
            _dbSet.Add(entity);
            if (isSaveChange)
            {
                return SaveChanges() > 0;
            }
            return false;
        }

        /// <summary>
        /// 异步插入
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="isSaveChange"></param>
        /// <returns></returns>
        public async Task<bool> InsertAsync(T entity, bool isSaveChange = true)
        {
            _dbSet.Add(entity);
            if (isSaveChange)
            {
                return await SaveChangesAsync() > 0;
            }
            return false;
        }


        public bool Insert(List<T> entitys, bool isSaveChange = true)
        {
            _dbSet.AddRange(entitys);
            if (isSaveChange)
            {
                return SaveChanges() > 0;
            }
            return false;
        }

        public async Task<bool> InsertAsync(List<T> entitys, bool isSaveChange = true)
        {
            _dbSet.AddRange(entitys);
            if (isSaveChange)
            {
                return await SaveChangesAsync() > 0;
            }
            return false;
        }
        #endregion

        #region 删除
        public bool Delete(List<T> entitys, bool isSaveChange = true)
        {
            entitys.ForEach(entity =>
            {
                _dbSet.Attach(entity);
                _dbSet.Remove(entity);
            });
            return isSaveChange && SaveChanges() > 0;
        }

        public virtual async Task<bool> DeleteAsync(T entity, bool isSaveChange = true)
        {
            _dbSet.Attach(entity);
            _dbSet.Remove(entity);
            return isSaveChange && await SaveChangesAsync() > 0;
        }
        public virtual async Task<bool> DeleteAsync(List<T> entitys, bool isSaveChange = true)
        {
            entitys.ForEach(entity =>
            {
                _dbSet.Attach(entity);
                _dbSet.Remove(entity);
            });
            return isSaveChange && await SaveChangesAsync() > 0;
        }
        #endregion

        #region 更新数据
        public bool Update(T entity, bool isSaveChange = true, List<string> updatePropertyList = null)
        {
            if (entity == null)
            {
                return false;
            }
            _dbSet.Attach(entity);
            var entry = _dbContext.Entry(entity);
            if (updatePropertyList == null)
            {
                entry.State = EntityState.Modified;//全字段更新
            }
            else
            {

                updatePropertyList.ForEach(c =>
                {
                    entry.Property(c).IsModified = true; //部分字段更新的写法
                });


            }
            if (isSaveChange)
            {
                return SaveChanges() > 0;
            }
            return false;
        }
        public bool Update(List<T> entitys, bool isSaveChange = true)
        {
            if (entitys == null || entitys.Count == 0)
            {
                return false;
            }
            entitys.ForEach(c =>
            {
                Update(c, false);
            });
            if (isSaveChange)
            {
                return SaveChanges() > 0;
            }
            return false;
        }
        public async Task<bool> UpdateAsync(T entity, bool isSaveChange, List<string> updatePropertyList)
        {
            if (entity == null)
            {
                return false;
            }
            _dbSet.Attach(entity);
            var entry = _dbContext.Entry<T>(entity);
            if (updatePropertyList == null)
            {
                entry.State = EntityState.Modified;//全字段更新
            }
            else
            {
                updatePropertyList.ForEach(c =>
                {
                    entry.Property(c).IsModified = true; //部分字段更新的写法
                });

            }
            if (isSaveChange)
            {
                return await SaveChangesAsync() > 0;
            }
            return false;
        }
        public async Task<bool> UpdateAsync(List<T> entitys, bool isSaveChange = true)
        {
            if (entitys == null || entitys.Count == 0)
            {
                return false;
            }
            entitys.ForEach(c =>
            {
                _dbSet.Attach(c);
                _dbContext.Entry(c).State = EntityState.Modified;
            });
            if (isSaveChange)
            {
                return await SaveChangesAsync() > 0;
            }
            return false;
        }


        #endregion

        #region SQL语句
#pragma warning disable CS0693 // 类型参数“T”与外部类型“Repositorys<T>”中的类型参数同名
        public virtual void BulkInsert<T>(List<T> entities)
#pragma warning restore CS0693 // 类型参数“T”与外部类型“Repositorys<T>”中的类型参数同名
        { }

        // [Obsolete]
        //public int ExecuteSql(string sql)
        //{
        //    return _dbContext.Database.ExecuteSqlCommand(sql);
        //}

        //[Obsolete]
        //public Task<int> ExecuteSqlAsync(string sql)
        //{
        //    return _dbContext.Database.ExecuteSqlCommandAsync(sql);
        //}

        //[Obsolete]
        //public int ExecuteSql(string sql, List<DbParameter> spList)
        //{
        //    return _dbContext.Database.ExecuteSqlCommand(sql, spList.ToArray());
        //}

        //[Obsolete]
        //public Task<int> ExecuteSqlAsync(string sql, List<DbParameter> spList)
        //{
        //    return _dbContext.Database.ExecuteSqlCommandAsync(sql, spList.ToArray());
        //}


        public virtual DataTable GetDataTableWithSql(string sql)
        {
            throw new NotImplementedException();
        }

        public virtual DataTable GetDataTableWithSql(string sql, List<DbParameter> spList)
        {
            throw new NotImplementedException();
        }



        IQueryable<T> IRepositorys<T>.GetAll()
        {
            return _dbSet.AsNoTracking();
        }

        public async Task<List<T>> GetAllAsync()
        {
            return await _dbSet.AsNoTracking().ToListAsync();
        }

#pragma warning disable CS1998 // 此异步方法缺少 "await" 运算符,将以同步方式运行。请考虑使用 "await" 运算符等待非阻止的 API 调用,或者使用 "await Task.Run(...)" 在后台线程上执行占用大量 CPU 的工作。
        public async Task<IQueryable<T>> WhereAsync(Expression<Func<T, bool>> where)
#pragma warning restore CS1998 // 此异步方法缺少 "await" 运算符,将以同步方式运行。请考虑使用 "await" 运算符等待非阻止的 API 调用,或者使用 "await Task.Run(...)" 在后台线程上执行占用大量 CPU 的工作。
        {
            return _dbSet.Where(@where);
        }

        public async Task<bool> UpdateAsync1(T entity, bool isSaveChange, string updatePropert)
        {
            if (entity == null)
            {
                return false;
            }
            _dbSet.Attach(entity);
            var entry = _dbContext.Entry(entity);
            if (updatePropert == null)
            {
                entry.State = EntityState.Modified;//全字段更新
            }
            else
            {
                entry.Property(updatePropert).IsModified = true; //部分字段更新的写法
            }
            if (isSaveChange)
            {
                return await SaveChangesAsync() > 0;
            }
            return false;
        }

        public async Task<int> CountAsync()
        {
            return await _dbSet.AsNoTracking().CountAsync();
        }

        public async Task<int> CountAsync(Expression<Func<T, bool>> where)
        {
            return await _dbSet.AsNoTracking().CountAsync(@where);
        }
        #endregion



    }
}

创建实例

添加RepositoryFactory类和IRepositoryFactory接口

IRepositoryFactory接口:

public interface IRepositoryFactory
{
    IRepositorys < T > CreateRepository < T > (IconcardContext mydbcontext) where T: class;
}

RepositoryFactory类:

public class RepositoryFactory: IRepositoryFactory
{
    public IRepositorys < T > CreateRepository < T > (IconcardContext mydbcontext) where T: class
    {
        return new Repositorys < T > (mydbcontext);
    }
}

Service层

添加BaseService类和IBaseService接口

IBaseService

public interface IBaseService
{
    IRepositorys < T > CreateService < T > () where T: class, new();
}

BaseService

public class BaseService: IBaseService
{
    private IRepositoryFactory _repositoryFactory;
    private IconcardContext _mydbcontext;
    public BaseService(IRepositoryFactory repositoryFactory, IconcardContext mydbcontext)
    {
        this._repositoryFactory = repositoryFactory;
        this._mydbcontext = mydbcontext;
    }
    public IRepositorys < T > CreateService < T > () where T: class, new()
    {
        return _repositoryFactory.CreateRepository < T > (_mydbcontext);
    }
}

添加Service模块xxxService类和IxxxService接口,xxxService类继承父类BaseService,生成构造函数。

//构造函数 自动生成
public TypechoService(IRepositoryFactory repositoryFactory, IconcardContext mydbcontext) : base(repositoryFactory, mydbcontext)
        {
        }

依赖注入

注册DbContext

services.AddDbContext < typechoContext > (options => options.UseMySql(Configuration.GetConnectionString("DefaultConnection")));\\
appsettings.json "ConnectionStrings":
{
    "DefaultConnection": "Server=localhost;database=typecho;uid=root;pwd=woshishui;"
}
services.AddScoped < IconcardContext, typechoContext > (); //dbc
services.AddScoped < IRepositoryFactory, RepositoryFactory > (); //泛型工厂
services.AddScoped < ITypechoTestService, TypechoService > (); //ioc

UI层调用

    public class ReSnArticleService : BaseService, IReSnArticleService
    {
        private readonly CacheUtil _cache;
        private int _resultInt;
        private List<Article> _resultList;

        public ReSnArticleService(ICacheUtil cacheUtil, IRepositoryFactory repositoryFactory, IConcardContext myDbcontext) : base(repositoryFactory, myDbcontext)
        {
            _cache = (CacheUtil)cacheUtil;
        }

        public async Task<int> CountAsync()
        {
            _resultInt = _cache.CacheNumber1("CountAsync", _resultInt);
            if (_resultInt == 0)
            {
                _resultInt = await CreateService<Article>().CountAsync();
                _cache.CacheNumber1("CountAsync", _resultInt);
            }
            return _resultInt;
        }
posted @ 2020-05-08 15:45  少年。  阅读(2329)  评论(1编辑  收藏  举报