首页 > 数据库 >NET7中sqlsugar的使用

NET7中sqlsugar的使用

时间:2023-07-17 23:56:10浏览次数:43  
标签:predicate Task TEntity entity 使用 NET7 Expression public 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<,>));

 

标签:predicate,Task,TEntity,entity,使用,NET7,Expression,public,sqlsugar
From: https://www.cnblogs.com/niunan/p/17561666.html

相关文章

  • HandlerMethodArgumentResolver方法参数解析器的使用
    一、使用场景介绍HandlerMethodArgumentResolver,中文称为方法参数解析器,是SpringWeb(SpringMVC)组件中的众多解析器之一,主要用来对Controller中方法的参数进行处理。在一般的接口调用场景下,每次调用Controller都需要检查请求中的token信息,并根据token还原用户信息,然后将用户信息封......
  • 如何使用 Amazon Systems Manager 集中管理 Amazon IoT Greengrass 设备
    对于边缘设备管理员来说,远程管理大量不同的系统和应用程序会是一项富有挑战性的任务。AmazonIoTGreengrass 可帮助这些系统管理员管理其边缘设备应用程序堆栈。不过,这些设备上的系统软件必须通过与其大型IT企业的运营策略一致的运营策略来单独更新和维护。此外,客户必须构建或......
  • 使用docker安装的tomcat部署activiti-app.war、activiti-admin.war失败(ClassNotFound
    背景一直以来习惯用docker配置一些本地学习环境,许多教程配置activiti的方式都是通过复制activiti的war包部署在tomcat中,我尝试了一下通过docker的方式遇到了一些不易察觉的错误。使用方式描述使用docker安装tomcat9.0dockerrun-d-p8080:8080--nametomcattomcat:9.0复......
  • 浅析vue3中如何使用动态组件、如何快速理解Vue3的 toRaw和markRaw、ref与shallowRef、
    一、Vue3中使用component:is加载动态组件1、不使用setup语法糖,这种方式和vue2差不多,is可以是个字符串2、使用setup语法糖,这时候的is如果使用字符串就会加载不出来,得使用组件实例<componentclass="task-box":is="componentObj[route.params.type]":info="taskInfo"></co......
  • Jetpack Compose:开始使用Model
    接上篇https://www.cnblogs.com/develon/p/17525925.html参考:https://juejin.cn/post/6844903982742126600Model概览......
  • Python中哈哈哈字符串的简单使用
    1defget_string(string,key):2chars=['。',',','.',',','\\n']3print("oldstr:"+string)4match=re.search(key,string)5ifmatch:6start=match.star......
  • springboot下使用rabbitMQ之开发配置方式(一)
    springboot下使用rabbitMQ之开发配置方式(一)距离上次发布博客已经小一年了,这次...嗯,没错,我又回来啦.........
  • 短信平台系统搭建中的通道接口使用逻辑-捷达云信
    当使用外放SMPP协议时,有几个优势值得注意:可扩展性:通过外放SMPP协议,您可以将短信处理负载转移到专门的服务提供商,他们通常具备高度可扩展的基础设施。这样可以确保在处理大量短信时不会对您的系统造成性能问题,并能够应对业务的快速增长。简化架构:通过外放SMPP协议,您可以将与SMPP......
  • 【Azure API Management】实现在API Management服务中使用MI(管理标识 Managed Identi
    问题描述在Azure的同一数据中心,APIManagement访问启用了防火墙的StorageAccount,并且把APIM的公网IP地址设置在白名单。但访问依旧是403原因是:存储帐户部署在同一区域中的服务使用专用的AzureIP地址进行通信。因此,不能基于特定的Azure服务的公共出站IP地址范围来限制......
  • postgresql + mybatis 使用中需要注意的问题
    1.mybatis是完全支持postgresql的。包括空间查询。<dependency><groupId>org.postgresql</groupId><artifactId>postgresql</artifactId><scope>runtime</scope></dependency>2.通过my......