NET7中sqlsugar的使用

NET7中sqlsugar的使用

仿《深入浅出ASP.NET CORE》这书里的IRepository和RepositoryBase

using SqlSugar;
using System.Linq.Expressions;

namespace WebApplication1.DAL
{
    /// <summary>
    /// 所有仓储的约定,此接口仅作为约定,用于标识他们
    /// </summary>
    /// <typeparam name="TEntity">传入仓储的实体模型</typeparam>
    /// <typeparam name="TPrimaryKey">传入仓储的主键类型</typeparam>
    public interface IRepository<TEntity, TPrimaryKey> where TEntity : class
    {
        #region 查询
        ISugarQueryable<TEntity> GetAll();
        List<TEntity> GetAllList();
        Task<List<TEntity>> GetAllListAsync();
        List<TEntity> GetAllList(Expression<Func<TEntity, bool>> predicate);
        Task<List<TEntity>> GetAllListAsync(Expression<Func<TEntity, bool>> predicate);
        TEntity FirstOrDefault(Expression<Func<TEntity, bool>> predicate);
        Task<TEntity> FirstOrDefaultAsycn(Expression<Func<TEntity, bool>> predicate);
        #endregion

        #region 新增
        void Insert(TEntity entity);
        Task InsertAsync(TEntity entity);
        #endregion

        #region 更新
        void Update(TEntity entity);
        Task UpdateAsync(TEntity entity);
        #endregion

        #region 删除
        void Delete(TEntity entity);
        Task DeleteAsync(TEntity entity);
        void Delete(Expression<Func<TEntity, bool>> predicate);
        Task DeleteAsync(Expression<Func<TEntity, bool>> predicate);
        #endregion

        #region 总和计算
        int Count();
        Task<int> CountAsync();
        int Count(Expression<Func<TEntity, bool>> predicate);
        Task<int> CountAsync(Expression<Func<TEntity, bool>> predicate);
        #endregion
    }
}
using System.Collections.Generic;
using System.Linq.Expressions;
using System;
using SqlSugar;

namespace WebApplication1.DAL
{
    /// <summary>
    /// 默认仓储的通用功能实现,用于所有的领域模型
    /// </summary>
    /// <typeparam name="TEntity"></typeparam>
    /// <typeparam name="TPrimaryKey"></typeparam>
    public class RepositoryBase<TEntity, TPrimaryKey> : IRepository<TEntity, TPrimaryKey> where TEntity : class
    {
        protected readonly ISqlSugarClient db;

        public RepositoryBase(ISqlSugarClient db)
        {
           this.db=db;
        }

    
        public int Count()
        {
            return GetAll().Count();
        }

        public int Count(Expression<Func<TEntity, bool>> predicate)
        {
            return GetAll().Where(predicate).Count();
        }

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

        public async Task<int> CountAsync(Expression<Func<TEntity, bool>> predicate)
        {
            return await GetAll().Where(predicate).CountAsync();
        }

        public void Delete(TEntity entity)
        {
           db.DeleteableByObject(entity).ExecuteCommand();
        }

        public async Task DeleteAsync(TEntity entity)
        {
            await db.DeleteableByObject(entity).ExecuteCommandAsync();
        }

        public void Delete(Expression<Func<TEntity, bool>> predicate)
        {
            foreach (var entity in GetAll().Where(predicate).ToList())
            {
                Delete(entity);
            }
        }

        public async Task DeleteAsync(Expression<Func<TEntity, bool>> predicate)
        {
            foreach (var entity in GetAll().Where(predicate).ToList())
            {
                await DeleteAsync(entity);
            }
        }

        public TEntity FirstOrDefault(Expression<Func<TEntity, bool>> predicate)
        {
            return GetAll().First(predicate);
        }

        public async Task<TEntity> FirstOrDefaultAsycn(Expression<Func<TEntity, bool>> predicate)
        {
            return await GetAll().FirstAsync(predicate);
        }

        public ISugarQueryable<TEntity> GetAll()
        {
            return db.Queryable<TEntity>();
        }

        public List<TEntity> GetAllList()
        {
            return GetAll().ToList();
        }

        public List<TEntity> GetAllList(Expression<Func<TEntity, bool>> predicate)
        {
            return GetAll().Where(predicate).ToList();
        }

        public async Task<List<TEntity>> GetAllListAsync()
        {
            return await GetAll().ToListAsync();
        }

        public async Task<List<TEntity>> GetAllListAsync(Expression<Func<TEntity, bool>> predicate)
        {
            return await GetAll().Where(predicate).ToListAsync();
        }

        public void Insert(TEntity entity)
        {
              db.InsertableByObject(entity).ExecuteCommand();
    
        }
 
     

        public async Task InsertAsync(TEntity entity)
        {
           await db.InsertableByObject(entity).ExecuteCommandAsync();

        }

        public void Update(TEntity entity)
        {
           db.UpdateableByObject(entity).ExecuteCommand();
        }

        public async Task UpdateAsync(TEntity entity)
        {
          await db.UpdateableByObject(entity).ExecuteCommandAsync();
        }


    }
}
            //注册上下文:AOP里面可以获取IOC对象,如果有现成框架比如Furion可以不写这一行
            builder.Services.AddHttpContextAccessor();
            //注册SqlSugar
            builder.Services.AddSingleton<ISqlSugarClient>(s =>
            {
                SqlSugarScope sqlSugar = new SqlSugarScope(new ConnectionConfig()
                {
                    DbType = SqlSugar.DbType.SqlServer,
                    ConnectionString = "server=.\\sqlexpress;uid=sa;pwd=123456;database=studentdb;pooling=true;min pool size=5;max pool size=100;TrustServerCertificate=true;",
                    IsAutoCloseConnection = true,
                },
               db =>
               {
                   //单例参数配置,所有上下文生效
                   db.Aop.OnLogExecuting = (sql, pars) =>
                   {
                       //获取IOC对象不要求在一个上下文
                       //vra log=s.GetService<Log>()

                       //获取IOC对象要求在一个上下文
                       //var appServive = s.GetService<IHttpContextAccessor>();
                       //var log= appServive?.HttpContext?.RequestServices.GetService<Log>();
                   };
               });
                return sqlSugar;
            });

            builder.Services.AddTransient(typeof(IRepository<,>), typeof(RepositoryBase<,>));