ASP.NET Core-SqlSugar

1.安装NuGet包SqlSugarCore

 

2.建立SqlSugarCore服务注入扩展

 public static IServiceCollection AddSqlSugar(this IServiceCollection services, IConfiguration configuration)
 {
     var config = configuration.GetSection("SqlConfig").Get<ConnectionConfig>();

     services.AddScoped<ISqlSugarClient>(s =>
     //services.AddScoped(s =>
     {

         var db = new SqlSugarClient(config, db =>
         {
             ////启用全局删除过滤器
             //config.MoreSettings = new ConnMoreSettings { IsAutoDeleteQueryFilter = true };
             //手动添加查询过滤器,查询时过滤掉软删除的数据
             db.QueryFilter.AddTableFilter<IDeletionAudited>(it => it.IsDeleted == false);
             db.GetConnection("Master").Aop.DataExecuting = DataExecuting;
             db.Aop.OnLogExecuting = (sql, pars) =>
             {
                 //获取原生SQL推荐 5.1.4.63  性能OK
                 Console.WriteLine(UtilMethods.GetNativeSql(sql, pars));

                 //获取无参数化SQL 对性能有影响,特别大的SQL参数多的,调试使用
                 //Console.WriteLine(UtilMethods.GetSqlString(DbType.SqlServer,sql,pars))
             };
         });
         return db;
     });
     return services;
 }

数据执行前事件

数据进入数据处理前针对不同的数据操作可对数据做处理

如下是

数据插入前对数据的创建时间、创建人填充值

数据更新操作前对数据的更新时间填充值

等等...

 /// <summary>
 /// 数据执行前事件
 /// </summary>
 /// <param name="oldVal"></param>
 /// <param name="entityInfo"></param>
 private static void DataExecuting(object oldVal, DataFilterModel entityInfo)
 {
     if (entityInfo.OperationType == DataFilterType.InsertByObject)
     {
         if (entityInfo.PropertyName == DataBaseConstants.CREATE_TIME)
         {
             entityInfo.SetValue(DateTime.Now);
         }
         if (entityInfo.PropertyName == DataBaseConstants.CREATE_USER)
         {
             //使用redis中缓存的用户信息填充
         }
     }

     if (entityInfo.OperationType == DataFilterType.UpdateByObject)
     {
         if (entityInfo.PropertyName == DataBaseConstants.UPDATE_TIME)
         {
             entityInfo.SetValue(DateTime.Now);
         }
         if (entityInfo.PropertyName == DataBaseConstants.UPDATE_USER)
         {
             //使用redis中缓存的用户信息填充
         }
     }

     if (entityInfo.OperationType == DataFilterType.DeleteByObject)
     {
         if (entityInfo.PropertyName == DataBaseConstants.DELETE_TIME)
         {
             entityInfo.SetValue(DateTime.Now);
         }
         if (entityInfo.PropertyName == DataBaseConstants.DELETE_USER)
         {
             //使用redis中缓存的用户信息填充
         }
         if (entityInfo.PropertyName == DataBaseConstants.DELETE_STATUS)
         {
             entityInfo.SetValue(1);
         }
     }
 }

 

3.Program.cs中注入sqlsugar服务

//数据库Orm
builder.Services.AddSqlSugar(configration);

 

posted @ 2024-07-16 16:54  流年sugar  阅读(19)  评论(0编辑  收藏  举报