public FreeSqlBuilder GetFreeSqlBuilder() { var freeSqlBuilder = new FreeSqlBuilder() .UseConnectionString(Options.FreeSqlGeneratorOptions.DatabaseType, Options.FreeSqlGeneratorOptions.ConnectionString); Options.FreeSqlDbContextOptions.EntityKey = Options.FreeSqlGeneratorOptions.ConnectionString; //基础配置 if (Options.FreeSqlGeneratorOptions.LazyLoading.HasValue) { freeSqlBuilder.UseGenerateCommandParameterWithLambda(Options.FreeSqlGeneratorOptions.LazyLoading.Value); } if (Options.FreeSqlGeneratorOptions.NoneCommandParameter.HasValue) { freeSqlBuilder.UseNoneCommandParameter(Options.FreeSqlGeneratorOptions.NoneCommandParameter.Value); } if (Options.FreeSqlGeneratorOptions.GenerateCommandParameterWithLambda.HasValue) { freeSqlBuilder.UseGenerateCommandParameterWithLambda(Options.FreeSqlGeneratorOptions.GenerateCommandParameterWithLambda.Value); } if (Options.FreeSqlGeneratorOptions.HandleCommandLog != null || Options.FreeSqlGeneratorOptions.MonitorCommandExecuting != null || Options.FreeSqlGeneratorOptions.MonitorCommandExecuted != null) { freeSqlBuilder.UseMonitorCommand( Options.FreeSqlGeneratorOptions.MonitorCommandExecuting ?? new Action <System.Data.Common.DbCommand>((cmd) => { }), Options.FreeSqlGeneratorOptions.MonitorCommandExecuted ?? new Action <System.Data.Common.DbCommand, string>((cmd, log) => { if (Options.FreeSqlGeneratorOptions.HandleCommandLog != null) { Options.FreeSqlGeneratorOptions.HandleCommandLog.Invoke(log); } })); } //开发配置 if (Options.FreeSqlDevOptions?.AutoSyncStructure.HasValue == true) { freeSqlBuilder.UseAutoSyncStructure(Options.FreeSqlDevOptions.AutoSyncStructure.Value); } if (Options.FreeSqlDevOptions?.SyncStructureNameConvert.HasValue == true) { freeSqlBuilder.UseNameConvert(Options.FreeSqlDevOptions.SyncStructureNameConvert.Value); } if (Options.FreeSqlDevOptions?.ConfigEntityFromDbFirst.HasValue == true) { freeSqlBuilder.UseConfigEntityFromDbFirst(Options.FreeSqlDevOptions.ConfigEntityFromDbFirst.Value); } Options.SetupBuilder?.Invoke(freeSqlBuilder); return(freeSqlBuilder); }
/// <summary> /// 创建FreeSql实例 /// </summary> /// <param name="user"></param> /// <param name="appConfig"></param> /// <param name="dbConfig"></param> /// <param name="tenant"></param> /// <returns></returns> private static IFreeSql CreateFreeSql(IUser user, AppConfig appConfig, DbConfig dbConfig, CreateFreeSqlTenantDto tenant) { var freeSqlBuilder = new FreeSqlBuilder() .UseConnectionString(tenant.DbType.Value, tenant.ConnectionString) .UseAutoSyncStructure(false) .UseLazyLoading(false) .UseNoneCommandParameter(true); #region 监听所有命令 if (dbConfig.MonitorCommand) { freeSqlBuilder.UseMonitorCommand(cmd => { }, (cmd, traceLog) => { Console.WriteLine($"{cmd.CommandText}\r\n"); }); } #endregion 监听所有命令 var fsql = freeSqlBuilder.Build(); fsql.GlobalFilter.Apply <IEntitySoftDelete>("SoftDelete", a => a.IsDeleted == false); //配置实体 DbHelper.ConfigEntity(fsql, appConfig); #region 监听Curd操作 if (dbConfig.Curd) { fsql.Aop.CurdBefore += (s, e) => { Console.WriteLine($"{e.Sql}\r\n"); }; } #endregion 监听Curd操作 #region 审计数据 //计算服务器时间 var serverTime = fsql.Select <DualEntity>().Limit(1).First(a => DateTime.UtcNow); var timeOffset = DateTime.UtcNow.Subtract(serverTime); fsql.Aop.AuditValue += (s, e) => { DbHelper.AuditValue(e, timeOffset, user); }; #endregion 审计数据 return(fsql); }
/// <summary> /// 添加数据库 /// </summary> /// <param name="services"></param> /// <param name="env"></param> public async static Task AddDbAsync(this IServiceCollection services, IHostEnvironment env) { var dbConfig = new ConfigHelper().Get <DbConfig>("dbconfig", env.EnvironmentName); //创建数据库 if (dbConfig.CreateDb) { await DbHelper.CreateDatabaseAsync(dbConfig); } #region FreeSql var freeSqlBuilder = new FreeSqlBuilder() .UseConnectionString(dbConfig.Type, dbConfig.ConnectionString) .UseAutoSyncStructure(false) .UseLazyLoading(false) .UseNoneCommandParameter(true); #region 监听所有命令 if (dbConfig.MonitorCommand) { freeSqlBuilder.UseMonitorCommand(cmd => { }, (cmd, traceLog) => { //Console.WriteLine($"{cmd.CommandText}\n{traceLog}\r\n"); Console.WriteLine($"{cmd.CommandText}\r\n"); }); } #endregion var fsql = freeSqlBuilder.Build(); //配置实体 var appConfig = new ConfigHelper().Get <AppConfig>("appconfig", env.EnvironmentName); DbHelper.ConfigEntity(fsql, appConfig); #region 初始化数据库 //同步结构 if (dbConfig.SyncStructure) { DbHelper.SyncStructure(fsql, dbConfig: dbConfig, appConfig: appConfig); } //同步数据 if (dbConfig.SyncData) { await DbHelper.SyncDataAsync(fsql, dbConfig); } #endregion //生成数据包 if (dbConfig.GenerateData && !dbConfig.CreateDb && !dbConfig.SyncData) { await DbHelper.GenerateSimpleJsonDataAsync(fsql); } #region 监听Curd操作 if (dbConfig.Curd) { fsql.Aop.CurdBefore += (s, e) => { Console.WriteLine($"{e.Sql}\r\n"); }; } #endregion #region 审计数据 //计算服务器时间 //var serverTime = fsql.Select<T>().Limit(1).First(a => DateTime.local); //var timeOffset = DateTime.UtcNow.Subtract(serverTime); var user = services.BuildServiceProvider().GetService <IUser>(); fsql.Aop.AuditValue += (s, e) => { if (user == null || user.Id <= 0) { return; } if (e.AuditValueType == FreeSql.Aop.AuditValueType.Insert) { switch (e.Property.Name) { case "CreatedUserId": e.Value = user.Id; break; case "CreatedUserName": e.Value = user.Name; break; case "TenantId": e.Value = user.TenantId; break; //case "CreatedTime": // e.Value = DateTime.Now.Subtract(timeOffset); // break; } } else if (e.AuditValueType == FreeSql.Aop.AuditValueType.Update) { switch (e.Property.Name) { case "ModifiedUserId": e.Value = user.Id; break; case "ModifiedUserName": e.Value = user.Name; break; //case "ModifiedTime": // e.Value = DateTime.Now.Subtract(timeOffset); // break; } } }; #endregion #endregion //导入多数据库 if (null != dbConfig.Dbs) { foreach (var multiDb in dbConfig.Dbs) { switch (multiDb.Name) { case nameof(MySqlDb): var mdb = CreateMultiDbBuilder(multiDb).Build <MySqlDb>(); services.AddSingleton(mdb); break; default: break; } } } }
/// <summary> /// 添加数据库 /// </summary> /// <param name="services"></param> /// <param name="env"></param> /// <param name="appConfig"></param> public async static void AddDb(this IServiceCollection services, IHostEnvironment env, AppConfig appConfig) { var dbConfig = new ConfigHelper().Get <DbConfig>("dbconfig", env.EnvironmentName); //创建数据库 if (dbConfig.CreateDb) { await DbHelper.CreateDatabase(dbConfig); } #region FreeSql var freeSqlBuilder = new FreeSqlBuilder() .UseConnectionString(dbConfig.Type, dbConfig.ConnectionString) .UseAutoSyncStructure(dbConfig.SyncStructure) .UseLazyLoading(false) .UseNoneCommandParameter(true); #region 监听所有命令 if (dbConfig.MonitorCommand) { freeSqlBuilder.UseMonitorCommand(cmd => { }, (cmd, traceLog) => { //Console.WriteLine($"{cmd.CommandText}\n{traceLog}\r\n"); Console.WriteLine($"{cmd.CommandText}\r\n"); }); } #endregion var fsql = freeSqlBuilder.Build(); //fsql.GlobalFilter.Apply<IEntitySoftDelete>("SoftDelete", a => a.IsDeleted == false); services.AddFreeRepository(filter => filter.Apply <IEntitySoftDelete>("SoftDelete", a => a.IsDeleted == false)); services.AddScoped <UnitOfWorkManager>(); services.AddSingleton(fsql); #region 初始化数据库 //同步结构 if (dbConfig.SyncStructure) { DbHelper.SyncStructure(fsql, dbConfig: dbConfig); } //同步数据 if (dbConfig.SyncData) { await DbHelper.SyncData(fsql, dbConfig); } #endregion //生成数据包 if (dbConfig.GenerateData && !dbConfig.CreateDb && !dbConfig.SyncData) { await DbHelper.GenerateSimpleJsonData(fsql); } #region 监听Curd操作 if (dbConfig.Curd) { fsql.Aop.CurdBefore += (s, e) => { System.Threading.Tasks.Parallel.For(0, 1, body => { Console.WriteLine($"{e.Sql}\r\n"); }); }; } #endregion #region 审计数据 //计算服务器时间 //var serverTime = fsql.Select<T>().Limit(1).First(a => DateTime.local); //var timeOffset = DateTime.UtcNow.Subtract(serverTime); var user = services.BuildServiceProvider().GetService <IUser>(); fsql.Aop.AuditValue += (s, e) => { if (user == null || user.Id <= 0) { return; } if (e.AuditValueType == FreeSql.Aop.AuditValueType.Insert) { switch (e.Property.Name) { case "CreatedUserId": e.Value = user.Id; break; case "CreatedUserName": e.Value = user.Name; break; //case "CreatedTime": // e.Value = DateTime.Now.Subtract(timeOffset); // break; } } else if (e.AuditValueType == FreeSql.Aop.AuditValueType.Update) { switch (e.Property.Name) { case "ModifiedUserId": e.Value = user.Id; break; case "ModifiedUserName": e.Value = user.Name; break; //case "ModifiedTime": // e.Value = DateTime.Now.Subtract(timeOffset); // break; } } }; #endregion #endregion Console.WriteLine($"{appConfig.Urls}\r\n"); }
/// <summary> /// 添加租户数据库 /// </summary> /// <param name="services"></param> /// <param name="env"></param> public static void AddTenantDb(this IServiceCollection services, IHostEnvironment env) { services.AddScoped <MyUnitOfWorkManager>(); var dbConfig = new ConfigHelper().Get <DbConfig>("dbconfig", env.EnvironmentName); var appConfig = new ConfigHelper().Get <AppConfig>("appconfig", env.EnvironmentName); var user = services.BuildServiceProvider().GetService <IUser>(); int idleTime = dbConfig.IdleTime > 0 ? dbConfig.IdleTime : 10; IdleBus <IFreeSql> ib = new IdleBus <IFreeSql>(TimeSpan.FromMinutes(idleTime)); var tenantName = AdminConsts.TenantName; if (appConfig.TenantType == TenantType.Own) { tenantName = "tenant_" + user.TenantId.ToString(); } ib.TryRegister(tenantName, () => { #region FreeSql var freeSqlBuilder = new FreeSqlBuilder() .UseConnectionString(dbConfig.Type, dbConfig.ConnectionString) .UseLazyLoading(false) .UseNoneCommandParameter(true); #region 监听所有命令 if (dbConfig.MonitorCommand) { freeSqlBuilder.UseMonitorCommand(cmd => { }, (cmd, traceLog) => { Console.WriteLine($"{cmd.CommandText}\r\n"); }); } #endregion var fsql = freeSqlBuilder.Build(); fsql.GlobalFilter.Apply <IEntitySoftDelete>("SoftDelete", a => a.IsDeleted == false); //配置实体 DbHelper.ConfigEntity(fsql, appConfig); //共享数据库 if (appConfig.TenantType == TenantType.Share) { fsql.GlobalFilter.ApplyIf <ITenant>("Tenant", () => user.TenantId > 0, a => a.TenantId == user.TenantId); } #region 监听Curd操作 if (dbConfig.Curd) { fsql.Aop.CurdBefore += (s, e) => { Console.WriteLine($"{e.Sql}\r\n"); }; } #endregion #region 审计数据 //计算服务器时间 var serverTime = fsql.Select <DualEntity>().Limit(1).First(a => DateTime.UtcNow); var timeOffset = DateTime.UtcNow.Subtract(serverTime); fsql.Aop.AuditValue += (s, e) => { if (user == null || user.Id <= 0) { return; } if (e.AuditValueType == FreeSql.Aop.AuditValueType.Insert) { switch (e.Property.Name) { case "CreatedUserId": e.Value = user.Id; break; case "CreatedUserName": e.Value = user.Name; break; case "TenantId": e.Value = user.TenantId; break; } if (e.Property.GetCustomAttribute <ServerTimeAttribute>(false) != null && (e.Column.CsType == typeof(DateTime) || e.Column.CsType == typeof(DateTime?)) && (e.Value == null || (DateTime)e.Value == default || (DateTime?)e.Value == default)) { e.Value = DateTime.Now.Subtract(timeOffset); } }
/// <summary> /// 添加租户数据库 /// </summary> /// <param name="services"></param> /// <param name="env"></param> public static void AddTenantDb(this IServiceCollection services, IHostEnvironment env) { services.AddScoped <MyUnitOfWorkManager>(); var dbConfig = new ConfigHelper().Get <DbConfig>("dbconfig", env.EnvironmentName); var appConfig = new ConfigHelper().Get <AppConfig>("appconfig", env.EnvironmentName); var user = services.BuildServiceProvider().GetService <IUser>(); int idleTime = dbConfig.IdleTime > 0 ? dbConfig.IdleTime : 10; IdleBus <IFreeSql> ib = new IdleBus <IFreeSql>(TimeSpan.FromMinutes(idleTime)); ib.TryRegister("tenant_" + user.TenantId.ToString(), () => { #region FreeSql var freeSqlBuilder = new FreeSqlBuilder() .UseConnectionString(dbConfig.Type, dbConfig.ConnectionString) .UseLazyLoading(false) .UseNoneCommandParameter(true); #region 监听所有命令 if (dbConfig.MonitorCommand) { freeSqlBuilder.UseMonitorCommand(cmd => { }, (cmd, traceLog) => { Console.WriteLine($"{cmd.CommandText}\r\n"); }); } #endregion var fsql = freeSqlBuilder.Build(); fsql.GlobalFilter.Apply <IEntitySoftDelete>("SoftDelete", a => a.IsDeleted == false); //共享数据库 if (appConfig.TenantType == TenantType.Share) { fsql.GlobalFilter.ApplyIf <ITenant>("Tenant", () => user.TenantId > 0, a => a.TenantId == user.TenantId); } #region 监听Curd操作 if (dbConfig.Curd) { fsql.Aop.CurdBefore += (s, e) => { Console.WriteLine($"{e.Sql}\r\n"); }; } #endregion #region 审计数据 fsql.Aop.AuditValue += (s, e) => { if (user == null || user.Id <= 0) { return; } if (e.AuditValueType == FreeSql.Aop.AuditValueType.Insert) { switch (e.Property.Name) { case "CreatedUserId": e.Value = user.Id; break; case "CreatedUserName": e.Value = user.Name; break; case "TenantId": e.Value = user.TenantId; break; } } else if (e.AuditValueType == FreeSql.Aop.AuditValueType.Update) { switch (e.Property.Name) { case "ModifiedUserId": e.Value = user.Id; break; case "ModifiedUserName": e.Value = user.Name; break; } } }; #endregion #endregion return(fsql); }); services.AddSingleton(ib); }
/// <summary> /// 添加数据库 /// </summary> /// <param name="services"></param> /// <param name="env"></param> public async static Task AddDbAsync(this IServiceCollection services, IHostEnvironment env) { services.AddScoped <MyUnitOfWorkManager>(); var dbConfig = new ConfigHelper().Get <DbConfig>("dbconfig", env.EnvironmentName); //创建数据库 if (dbConfig.CreateDb) { await DbHelper.CreateDatabaseAsync(dbConfig); } #region FreeSql var freeSqlBuilder = new FreeSqlBuilder() .UseConnectionString(dbConfig.Type, dbConfig.ConnectionString) .UseAutoSyncStructure(false) .UseLazyLoading(false) .UseNoneCommandParameter(true); #region 监听所有命令 if (dbConfig.MonitorCommand) { freeSqlBuilder.UseMonitorCommand(cmd => { }, (cmd, traceLog) => { //Console.WriteLine($"{cmd.CommandText}\n{traceLog}\r\n"); Console.WriteLine($"{cmd.CommandText}\r\n"); }); } #endregion 监听所有命令 var fsql = freeSqlBuilder.Build(); //配置实体 var appConfig = new ConfigHelper().Get <AppConfig>("appconfig", env.EnvironmentName); DbHelper.ConfigEntity(fsql, appConfig); #region 初始化数据库 //同步结构 if (dbConfig.SyncStructure) { DbHelper.SyncStructure(fsql, dbConfig: dbConfig, appConfig: appConfig); } #region 审计数据 //计算服务器时间 var serverTime = fsql.Select <DualEntity>().Limit(1).First(a => DateTime.UtcNow); var timeOffset = DateTime.UtcNow.Subtract(serverTime); var user = services.BuildServiceProvider().GetService <IUser>(); DbHelper.TimeOffset = timeOffset; fsql.Aop.AuditValue += (s, e) => { DbHelper.AuditValue(e, timeOffset, user); }; #endregion 审计数据 //同步数据 if (dbConfig.SyncData) { await DbHelper.SyncDataAsync(fsql, dbConfig, appConfig); } #endregion 初始化数据库 //生成数据包 if (dbConfig.GenerateData && !dbConfig.CreateDb && !dbConfig.SyncData) { await DbHelper.GenerateSimpleJsonDataAsync(fsql, appConfig); } #region 监听Curd操作 if (dbConfig.Curd) { fsql.Aop.CurdBefore += (s, e) => { Console.WriteLine($"{e.Sql}\r\n"); }; } #endregion 监听Curd操作 if (appConfig.Tenant) { fsql.GlobalFilter.Apply <ITenant>("Tenant", a => a.TenantId == user.TenantId); } #endregion FreeSql services.AddSingleton(fsql); //导入多数据库 if (null != dbConfig.Dbs) { foreach (var multiDb in dbConfig.Dbs) { switch (multiDb.Name) { case nameof(MySqlDb): var mdb = CreateMultiDbBuilder(multiDb).Build <MySqlDb>(); services.AddSingleton(mdb); break; default: break; } } } }
/// <summary> /// 添加数据库 /// </summary> /// <param name="services"></param> /// <param name="dbConfig"></param> /// <returns></returns> public async static Task AddDbAsync(this IServiceCollection services) { var codeSettings = new ConfigHelper().Get <CodeSettings>("codesettings", AppContext.BaseDirectory); var dbConfig = services.BuildServiceProvider().GetRequiredService <IOptions <DbConfig> >().Value; //创建数据库 if (dbConfig.CreateDb && codeSettings.InitDb) { await DbHelper.CreateDatabase(dbConfig); } #region FreeSql var freeSqlBuilder = new FreeSqlBuilder() .UseConnectionString(dbConfig.Type, dbConfig.ConnectionString) .UseAutoSyncStructure(dbConfig.SyncStructure && codeSettings.InitDb) .UseLazyLoading(false) .UseNoneCommandParameter(true); #region 监听所有命令 if (dbConfig.MonitorCommand && codeSettings.InitDb) { freeSqlBuilder.UseMonitorCommand(cmd => { }, (cmd, traceLog) => { //Console.WriteLine($"{cmd.CommandText}\n{traceLog}\r\n"); Console.WriteLine($"{cmd.CommandText}\r\n"); }); } #endregion var fsql = freeSqlBuilder.Build(); #region 初始化数据库 //同步结构 if (dbConfig.SyncStructure && codeSettings.InitDb) { DbHelper.SyncStructure(fsql, dbConfig: dbConfig); } //同步数据 if (dbConfig.SyncData && codeSettings.InitDb) { await DbHelper.SyncData(fsql, dbConfig); } #endregion //生成数据包 if (dbConfig.GenerateData && !dbConfig.CreateDb && !dbConfig.SyncData) { await DbHelper.GenerateSimpleJsonData(fsql); } #region 监听Curd操作 if (dbConfig.Curd && codeSettings.InitDb) { fsql.Aop.CurdBefore += (s, e) => { Console.WriteLine($"{e.Sql}\r\n"); }; } #endregion #region 审计数据 /* * //计算服务器时间 * var serverTime = fsql.Select<T>().Limit(1).First(a => DateTime.local); * var timeOffset = DateTime.UtcNow.Subtract(serverTime); * fsql.Aop.AuditValue += (s, e) => * { * if (e.AuditValueType == FreeSql.Aop.AuditValueType.Insert) * { * switch (e.Property.Name) * { * case "CreatedTime": * e.Value = DateTime.Now.Subtract(timeOffset); * break; * } * } * else if (e.AuditValueType == FreeSql.Aop.AuditValueType.Update) * { * switch (e.Property.Name) * { * case "ModifiedTime": * e.Value = DateTime.Now.Subtract(timeOffset); * break; * } * } * }; */ #endregion services.AddSingleton(fsql); #endregion codeSettings.InitDb = false; SuperCodeHelper.SaveSettings(codeSettings); }
/// <summary> /// 添加租户数据库 /// </summary> /// <param name="services"></param> /// <param name="env"></param> public static void AddTenantDb(this IServiceCollection services, IHostEnvironment env) { services.AddScoped <MyUnitOfWorkManager>(); var dbConfig = new ConfigHelper().Get <DbConfig>("dbconfig", env.EnvironmentName); var appConfig = new ConfigHelper().Get <AppConfig>("appconfig", env.EnvironmentName); var user = services.BuildServiceProvider().GetService <IUser>(); int idleTime = dbConfig.IdleTime > 0 ? dbConfig.IdleTime : 10; IdleBus <IFreeSql> ib = new IdleBus <IFreeSql>(TimeSpan.FromMinutes(idleTime)); var tenantName = AdminConsts.TenantName; if (appConfig.TenantType == TenantType.Own) { tenantName = "tenant_" + user.TenantId?.ToString(); } ib.TryRegister(tenantName, () => { #region FreeSql var freeSqlBuilder = new FreeSqlBuilder() .UseConnectionString(dbConfig.Type, dbConfig.ConnectionString) .UseAutoSyncStructure(false) .UseLazyLoading(false) .UseNoneCommandParameter(true); #region 监听所有命令 if (dbConfig.MonitorCommand) { freeSqlBuilder.UseMonitorCommand(cmd => { }, (cmd, traceLog) => { Console.WriteLine($"{cmd.CommandText}\r\n"); }); } #endregion var fsql = freeSqlBuilder.Build(); fsql.GlobalFilter.Apply <IEntitySoftDelete>("SoftDelete", a => a.IsDeleted == false); //配置实体 DbHelper.ConfigEntity(fsql, appConfig); //共享数据库 if (appConfig.TenantType == TenantType.Share) { fsql.GlobalFilter.ApplyIf <ITenant>("Tenant", () => user.TenantId > 0, a => a.TenantId == user.TenantId); } #region 监听Curd操作 if (dbConfig.Curd) { fsql.Aop.CurdBefore += (s, e) => { Console.WriteLine($"{e.Sql}\r\n"); }; } #endregion #region 审计数据 //计算服务器时间 var serverTime = fsql.Select <DualEntity>().Limit(1).First(a => DateTime.UtcNow); var timeOffset = DateTime.UtcNow.Subtract(serverTime); fsql.Aop.AuditValue += (s, e) => { DbHelper.AuditValue(e, timeOffset, user); }; #endregion #endregion return(fsql); }); services.AddSingleton(ib); }
/// <summary> /// 添加数据库配置 /// </summary> /// <param name="services"></param> /// <param name="appConfig"></param> public static void AddFreesql(this IServiceCollection services, AppConfig appConfig, DbConfig dbConfig) { _services = services; //创建数据库 if (dbConfig.CreateDb) { //await DbHelper.CreateDatabase(dbConfig); } #region FreeSql var freeSqlBuilder = new FreeSqlBuilder() .UseConnectionString(dbConfig.Type, dbConfig.ConnectionString) .UseAutoSyncStructure(dbConfig.SyncStructure) .UseLazyLoading(false) .UseNoneCommandParameter(true); #region 监听所有命令 if (dbConfig.MonitorCommand) { freeSqlBuilder.UseMonitorCommand(cmd => { }, (cmd, traceLog) => { //Console.WriteLine($"{cmd.CommandText}\n{traceLog}\r\n"); Console.WriteLine($"{cmd.CommandText}\r\n"); }); } #endregion var fsql = freeSqlBuilder.Build(); services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); services.AddSingleton <IUser, User>(); services.AddFreeRepository(filter => filter.Apply <IEntitySoftDelete>("SoftDelete", a => a.IsDeleted == false)); services.AddScoped <UnitOfWorkManager>(); services.AddSingleton(fsql); services.AddSingleton <ISysFileResponsitory, SysFileResponsitory>(); services.AddSingleton <ISysDicResponsitory, SysDicResponsitory>(); #region 初始化数据库 //同步数据 if (dbConfig.SyncData) { //await DbHelper.SyncData(fsql, dbConfig); } #endregion //生成数据包 if (dbConfig.GenerateData && !dbConfig.CreateDb && !dbConfig.SyncData) { //await DbHelper.GenerateSimpleJsonData(fsql); } List <string> _md5s = new List <string>(); #region 监听Curd操作 if (dbConfig.Curd) { fsql.Aop.CurdBefore += (s, e) => { Console.WriteLine($"{e.Sql}\r\n"); }; } fsql.Aop.CurdAfter += (s, e) => { if (e.CurdType == FreeSql.Aop.CurdType.Insert || e.CurdType == FreeSql.Aop.CurdType.Update) { //文件,更新为已使用 if (_md5s.Any() && e.EntityType != typeof(SysFile)) { var file = services.BuildServiceProvider().GetService <ISysFileResponsitory>(); file.UpdateDiy.Set(p => p.Used, true).Where(p => _md5s.Contains(p.Md5) && p.Uploaded && !p.Used).ExecuteAffrows(); _md5s.Clear(); } } if (e.ElapsedMilliseconds > 3000) { //TODO 慢SQL提醒开发者 Console.WriteLine($"慢Sql:{e.Sql}\r\n"); } }; #endregion #region 审计数据 fsql.Aop.AuditValue += (s, e) => { if (e.AuditValueType == FreeSql.Aop.AuditValueType.Insert || e.AuditValueType == FreeSql.Aop.AuditValueType.Update) { //更新文件为已使用 if (e.Property.GetCustomAttributes(typeof(FileAttribute), false).Any()) { if (e.Value != null && !_md5s.Any(p => p == e.Value.ToString())) { _md5s.Add(e.Value.ToString()); } } var user = services.BuildServiceProvider().GetService <IUser>(); if (user == null || !(user.Id > 0)) { return; } if (e.AuditValueType == FreeSql.Aop.AuditValueType.Insert) { switch (e.Property.Name) { case "CreatedUserId": e.Value = user.Id; break; case "CreatedUserName": e.Value = user.RealName; break; case "CreatedTime": e.Value = DateTime.Now; break; } } switch (e.Property.Name) { case "ModifiedUserId": e.Value = user.Id; break; case "ModifiedUserName": e.Value = user.Name; break; case "ModifiedTime": e.Value = DateTime.Now; break; } } }; #endregion #endregion }