init commit

This commit is contained in:
路 范
2022-03-30 17:54:33 +08:00
parent df01841625
commit 904bdd16cd
500 changed files with 217251 additions and 0 deletions

View File

@@ -0,0 +1,192 @@
using Ewide.Core;
using Ewide.Core.Service;
using Ewide.Core.Util;
using Ewide.EntityFramework.Core.SqlSugar;
using Furion;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Furion.JsonSerialization;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Microsoft.Extensions.Caching.Distributed;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Ewide.EntityFramework.Core
{
[AppDbContext("DefaultConnection", DbProvider.MySql)]
public class DefaultDbContext : AppDbContext<DefaultDbContext>, IModelBuilderFilter
{
public DefaultDbContext(DbContextOptions<DefaultDbContext> options) : base(options)
{
// 启用实体数据更改监听
EnabledEntityChangedListener = true;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseMySql(GetDatabaseConnectionString(), ServerVersion.FromString("5.5.53"));
base.OnConfiguring(optionsBuilder);
}
public string GetDatabaseConnectionString()
{
var connList = App.GetConfig<List<MutiDBConnectionString>>("ConnectionStrings")?.Where(p => p.Enabled).ToList();
var defaultConnection = connList.Find(a => a.Id == "118_3310_ewide")?.ConnectionString;// App.Configuration["ConnectionStrings:DefaultConnection"];
// 如果没有实现多租户方式,则无需查询
if (!typeof(IPrivateMultiTenant).IsAssignableFrom(GetType())) return defaultConnection;
// 判断 HttpContext 是否存在
var httpContext = App.HttpContext;
if (httpContext == null) return defaultConnection;
// 当前根据主机名称获取租户信息(可自由处理,比如请求参数等)
var host = httpContext.Request.Host.Value;
// 从分布式缓存中读取或查询数据库
var tenantCachedKey = $"MULTI_TENANT:{host}";
var distributedCache = App.GetService<IDistributedCache>();
var cachedValue = distributedCache.GetString(tenantCachedKey);
var jsonSerializerProvider = App.GetService<IJsonSerializerProvider>();
SysTenant currentTenant;
if (string.IsNullOrEmpty(cachedValue))
{
currentTenant = Db.GetDbContext<MultiTenantDbContextLocator>().Set<SysTenant>().FirstOrDefault(u => u.Host == host);
if (currentTenant != null)
distributedCache.SetString(tenantCachedKey, jsonSerializerProvider.Serialize(currentTenant));
}
else currentTenant = jsonSerializerProvider.Deserialize<SysTenant>(cachedValue);
return currentTenant?.Connection ?? defaultConnection;
}
/// <summary>
/// 配置假删除过滤器
/// </summary>
/// <param name="modelBuilder"></param>
/// <param name="entityBuilder"></param>
/// <param name="dbContext"></param>
/// <param name="dbContextLocator"></param>
public void OnCreating(ModelBuilder modelBuilder, EntityTypeBuilder entityBuilder, DbContext dbContext, Type dbContextLocator)
{
//var expression = base.FakeDeleteQueryFilterExpression(entityBuilder, dbContext);
//if (expression == null) return;
//entityBuilder.HasQueryFilter(expression);
}
/// <summary>
/// 重写实体保存之前
/// </summary>
/// <param name="eventData"></param>
/// <param name="result"></param>
protected override void SavingChangesEvent(DbContextEventData eventData, InterceptionResult<int> result)
{
var dbContext = eventData.Context;
// 获取所有更改,删除,新增的实体,但排除审计实体(避免死循环)
var entities = dbContext.ChangeTracker.Entries()
.Where(u => u.Entity.GetType() != typeof(SysLogAudit) && u.Entity.GetType() != typeof(SysLogOp) && u.Entity.GetType() != typeof(SysLogVis) &&
(u.State == EntityState.Modified || u.State == EntityState.Deleted || u.State == EntityState.Added))
.ToList();
if (entities == null || entities.Count < 1) return;
// 判断是否是演示环境
var demoEnvFlag = App.GetService<ISysConfigService>().GetDemoEnvFlag().GetAwaiter().GetResult();
if (demoEnvFlag)
{
var sysUser = entities.Find(u => u.Entity.GetType() == typeof(SysUser));
if (sysUser == null || string.IsNullOrEmpty((sysUser.Entity as SysUser).LastLoginTime.ToString())) // 排除登录
throw Oops.Oh(ErrorCode.D1200);
}
// 当前操作用户信息
var userId = App.User.FindFirst(ClaimConst.CLAINM_USERID)?.Value;
var userName = App.User.FindFirst(ClaimConst.CLAINM_ACCOUNT)?.Value;
foreach (var entity in entities)
{
if (entity.Entity.GetType().IsSubclassOf(typeof(DEntityBase)))
{
var obj = entity.Entity as DEntityBase;
if (entity.State == EntityState.Added)
{
obj.Id = string.IsNullOrEmpty(obj.Id) ? Guid.NewGuid().ToString() : obj.Id;
obj.CreatedTime = DateTime.Now;
if (!string.IsNullOrEmpty(userId))
{
obj.CreatedUserId = userId;
obj.CreatedUserName = userName;
}
}
else if (entity.State == EntityState.Modified)
{
obj.UpdatedTime = DateTime.Now;
obj.UpdatedUserId = userId;
obj.UpdatedUserName = userName;
}
}
//// 获取实体当前(现在)的值
//var currentValues = entity.CurrentValues;
//// 获取数据库中实体的值
//var databaseValues = entity.GetDatabaseValues();
//// 获取所有实体有效属性,排除 [NotMapper] 属性
//var props = entity.OriginalValues.Properties;
//foreach (var prop in props)
//{
// var propName = prop.Name; // 获取属性名
// var newValue = currentValues[propName]; // 获取现在的实体值
// object oldValue = null;
// // 如果是新增数据,则 databaseValues 为空,所以需要判断一下
// if (databaseValues != null)
// oldValue = databaseValues[propName];
// if ((newValue == oldValue) || (newValue != null && newValue.Equals(oldValue))) continue;
// // 插入审计日志表
// dbContext.AddAsync(new SysLogAudit
// {
// TableName = entity.Entity.GetType().Name, // 获取实体类型(表名)
// ColumnName = propName,
// NewValue = newValue?.ToString(),
// OldValue = oldValue?.ToString(),
// CreatedTime = DateTime.Now,
// UserId = userId,
// UserName = userName,
// Operate = entity.State.ToString() // 操作方式:新增、更新、删除
// });
//}
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
if (App.HostEnvironment.EnvironmentName == "Testing") return;
//集成测试下面代码会报错
#if DEBUG
XmlSerializerUtil xmlHandler = new XmlSerializerUtil();
Dictionary<Type, object> dic = xmlHandler.ReaderALL();
foreach (KeyValuePair<Type, object> item in dic)
{
List<object> data = new List<object>();
var collection = item.Value as System.Collections.IEnumerable;
if (collection != null)
{
foreach (var obj in collection)
{
data.Add(obj);
}
}
modelBuilder.Entity(item.Key).HasData(data);
}
#endif
}
}
}

View File

@@ -0,0 +1,66 @@
using Ewide.Core;
using Ewide.Core.Service;
using Furion;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using System;
using System.Linq;
namespace Ewide.EntityFramework.Core
{
[AppDbContext("MultiTenantConnection", DbProvider.Sqlite)]
public class MultiTenantDbContext : AppDbContext<MultiTenantDbContext, MultiTenantDbContextLocator>
{
public MultiTenantDbContext(DbContextOptions<MultiTenantDbContext> options) : base(options)
{
}
protected override void SavingChangesEvent(DbContextEventData eventData, InterceptionResult<int> result)
{
// 获取所有已更改的实体
var entities = eventData.Context.ChangeTracker.Entries()
.Where(u => u.State == EntityState.Modified || u.State == EntityState.Deleted || u.State == EntityState.Added)
.ToList();
// 判断是否是演示环境
var demoEnvFlag = App.GetService<ISysConfigService>().GetDemoEnvFlag().GetAwaiter().GetResult();
if (demoEnvFlag)
{
var sysUser = entities.Find(u => u.Entity.GetType() == typeof(SysUser));
if (sysUser == null || string.IsNullOrEmpty((sysUser.Entity as SysUser).LastLoginTime.ToString())) // 排除登录
throw Oops.Oh(ErrorCode.D1200);
}
// 当前操作用户信息
var userId = App.User.FindFirst(ClaimConst.CLAINM_USERID)?.Value;
var userName = App.User.FindFirst(ClaimConst.CLAINM_ACCOUNT)?.Value;
foreach (var entity in entities)
{
if (entity.Entity.GetType().IsSubclassOf(typeof(DEntityBase)))
{
var obj = entity.Entity as DEntityBase;
if (entity.State == EntityState.Added)
{
obj.Id = Guid.NewGuid().ToString();
obj.CreatedTime = DateTime.Now;
if (!string.IsNullOrEmpty(userId))
{
obj.CreatedUserId = userId;
obj.CreatedUserName = userName;
}
}
else if (entity.State == EntityState.Modified)
{
obj.UpdatedTime = DateTime.Now;
obj.UpdatedUserId = userId;
obj.UpdatedUserName = userName;
}
}
}
}
}
}

View File

@@ -0,0 +1,38 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<None Remove="dbsettings.Development.json" />
<None Remove="dbsettings.json" />
<None Remove="dbsettings.Production.json" />
<None Remove="sqlsettings.json" />
</ItemGroup>
<ItemGroup>
<Content Include="dbsettings.Production.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="dbsettings.Development.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="dbsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Data.SqlClient" Version="3.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="5.0.5" />
<PackageReference Include="MySql.Data" Version="8.0.25" />
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="5.0.0-alpha.2" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Ewide.Core\Ewide.Core.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,76 @@
using Furion;
using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ewide.EntityFramework.Core.SqlSugar
{
public static class SqlsugarSetup
{
public static void AddSqlsugarSetup(this IServiceCollection services)
{
var connList = App.GetConfig<List<MutiDBConnectionString>>("ConnectionStrings")?.Where(p => p.Enabled).ToList();
List<ConnectionConfig> connectConfigList = new();
connList.ForEach(conn =>
{
connectConfigList.Add(new ConnectionConfig
{
ConfigId = conn.Id,
ConnectionString = conn.ConnectionString,
DbType = conn.DbType,
IsAutoCloseConnection = true,
InitKeyType = InitKeyType.Attribute
});
});
services.AddSqlSugar(connectConfigList.ToArray(), db =>
{
//处理日志事务
db.Aop.OnLogExecuting = (sql, pars) =>
{
Debugger.Log(1, "", $"===================CurrentConfigId:{db.CurrentConnectionConfig.ConfigId} SqlSugar log started ===================\r\n");
Debugger.Log(2, "语句:", sql);
Debugger.Log(3, "参数:", string.Join(",", pars?.Select(it => it.ParameterName + ":" + it.Value)));
Debugger.Log(4, "", $"===================CurrentConfigId:{db.CurrentConnectionConfig.ConfigId} SqlSugar log end ===================\r\n");
//App.PrintToMiniProfiler("SqlSugar", "Info", sql + "\r\n" + db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
};
});
////如果多个数数据库传 List<ConnectionConfig>
//var configConnection = new ConnectionConfig()
//{
// DbType = SqlSugar.DbType.MySql,
// ConnectionString = configuration.GetConnectionString(dbName),
// IsAutoCloseConnection = true,
//};
//SqlSugarScope sqlSugar = new SqlSugarScope(configConnection,
// db =>
// {
// //单例参数配置,所有上下文生效
// db.Aop.OnLogExecuting = (sql, pars) =>
// {
// //Console.WriteLine(sql);//输出sql
// };
// });
//services.AddSingleton<ISqlSugarClient>(sqlSugar);//这边是SqlSugarScope用AddSingleton
}
}
public class MutiDBConnectionString
{
public string Id { get; set; }
public string ConnectionString { get; set; }
public DbType DbType { get; set; }
public bool Enabled { get; set; }
public string ProviderName { get; set; }
}
}

View File

@@ -0,0 +1,77 @@
using Dapper;
using Ewide.EntityFramework.Core.SqlSugar;
using Furion;
using Furion.DatabaseAccessor;
using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace Ewide.EntityFramework.Core
{
public class Startup : AppStartup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddDatabaseAccessor(options =>
{
options.CustomizeMultiTenants(); // 自定义租户
options.AddDb<DefaultDbContext>();
options.AddDb<MultiTenantDbContext, MultiTenantDbContextLocator>();
}, "Ewide.Database.Migrations");
var connList = App.GetConfig<List<MutiDBConnectionString>>("ConnectionStrings")?.Where(p => p.Enabled).ToList();
// 注册dapper, 目前只能强行写死连接字符串和数据库程序集
services.AddDapper(connList.Find(a => a.Id == "118_3310_ewide")?.ConnectionString, SqlProvider.MySql);
//sqlsugar的注册代码放到了SqlSugar文件夹里
services.AddSqlsugarSetup();
//List<ConnectionConfig> connectConfigList = new()
//{
// new ConnectionConfig
// {
// ConnectionString = App.Configuration["SqlServerConnectionString:DefaultConnection"],
// DbType = DbType.SqlServer,
// IsAutoCloseConnection = true,
// InitKeyType = InitKeyType.Attribute,
// ConfigId = "0",
// AopEvents = new AopEvents
// {
// OnLogExecuting = (sql, pars) =>
// {
// Debugger.Log(1, "", "=============================== SqlSugar log started ===============================\r\n");
// Debugger.Log(2, "语句:", sql);
// Debugger.Log(3, "参数:", string.Join(",", pars?.Select(it => it.ParameterName + ":" + it.Value)));
// Debugger.Log(4, "", "=============================== SqlSugar log end ===============================\r\n");
// }
// }
// },
// new ConnectionConfig
// {
// ConnectionString = App.Configuration["ConnectionStrings:RoadflowConnection"],
// DbType = DbType.MySql,
// IsAutoCloseConnection = true,
// InitKeyType = InitKeyType.Attribute,
// ConfigId = "RoadFlowDB",
// AopEvents = new AopEvents
// {
// OnLogExecuting = (sql, pars) =>
// {
// Debugger.Log(1, "", "=============================== Roadflow SqlSugar log started ===============================\r\n");
// Debugger.Log(2, "语句:", sql);
// Debugger.Log(3, "参数:", string.Join(",", pars?.Select(it => it.ParameterName + ":" + it.Value)));
// Debugger.Log(4, "", "=============================== SqlSugar log end ===============================\r\n");
// },
// }
// }
//};
//services.AddSqlSugar(connectConfigList.ToArray());
}
}
}

View File

@@ -0,0 +1,56 @@
{
//DefaultConnection这个节点不能删
"DefaultConnection": "",
"ConnectionStrings": [
/*
MySql = 0,
SqlServer = 1,
Sqlite = 2,
Oracle = 3,
PostgreSQL = 4,
Dm = 5,
Kdbndp = 6
*/
{
"Id": 1, // 连接id可以配置到数据库
"DBType": 2, // db类型枚举具体的看上边
"Enabled": false, // 是否开启当前数据库db
"Connection": "WMBlog.db" // 连接字符串
},
{
//目前使用的数据库
"Id": "118_3310_ewide",
"DBType": 0,
"Enabled": true,
"ConnectionString": "Data Source=118.178.224.202;Port=3310;Database=ewide;User ID=root;Password=root.Ewide;pooling=true;sslmode=none;CharSet=utf8;"
},
{
//郑总的线上测试数据库
"Id": "zhengzong_testdb",
"DBType": 0,
"Enabled": true,
"ConnectionString": "Data Source=42.192.248.196;Port=3306;Database=roadflow;User ID=joy;Password=db2202;pooling=true;sslmode=none;CharSet=utf8;"
},
{
//118上合并roadflow之前的数据库
"Id": "118_3306_old_ewide",
"DBType": 0,
"Enabled": true,
"ConnectionString": "Data Source=118.178.224.202;Port=3306;Database=ewide;User ID=root;Password=root;pooling=true;sslmode=none;CharSet=utf8;"
},
{
//不知道干什么用的
"Id": "PgSqlConnection",
"DBType": 4,
"Enabled": true,
"ConnectionString": "HOST=127.0.0.1;PORT=5432;DATABASE=ewide;PASSWORD=postgres;USER ID=postgres;"
},
{
"Id": "MultiTenantConnection",
"DBType": 2,
"Enabled": true,
"ConnectionString": "Data Source=./Dilon_SaaS.db"
}
]
}

View File

@@ -0,0 +1,56 @@
{
//DefaultConnection这个节点不能删
"DefaultConnection": "",
"ConnectionStrings": [
/*
MySql = 0,
SqlServer = 1,
Sqlite = 2,
Oracle = 3,
PostgreSQL = 4,
Dm = 5,
Kdbndp = 6
*/
{
"Id": 1, // 连接id可以配置到数据库
"DBType": 2, // db类型枚举具体的看上边
"Enabled": false, // 是否开启当前数据库db
"Connection": "WMBlog.db" // 连接字符串
},
{
//目前使用的数据库
"Id": "118_3310_ewide",
"DBType": 0,
"Enabled": true,
"ConnectionString": "Data Source=118.178.224.202;Port=3310;Database=ewide;User ID=root;Password=root.Ewide;pooling=true;sslmode=none;CharSet=utf8;"
},
{
//郑总的线上测试数据库
"Id": "zhengzong_testdb",
"DBType": 0,
"Enabled": true,
"ConnectionString": "Data Source=42.192.248.196;Port=3306;Database=roadflow;User ID=joy;Password=db2202;pooling=true;sslmode=none;CharSet=utf8;"
},
{
//118上合并roadflow之前的数据库
"Id": "118_3306_old_ewide",
"DBType": 0,
"Enabled": true,
"ConnectionString": "Data Source=118.178.224.202;Port=3306;Database=ewide;User ID=root;Password=root;pooling=true;sslmode=none;CharSet=utf8;"
},
{
//不知道干什么用的
"Id": "PgSqlConnection",
"DBType": 4,
"Enabled": true,
"ConnectionString": "HOST=127.0.0.1;PORT=5432;DATABASE=ewide;PASSWORD=postgres;USER ID=postgres;"
},
{
"Id": "MultiTenantConnection",
"DBType": 2,
"Enabled": true,
"ConnectionString": "Data Source=./Dilon_SaaS.db"
}
]
}

View File

@@ -0,0 +1,56 @@
{
//DefaultConnection这个节点不能删
"DefaultConnection": "",
"ConnectionStrings": [
/*
MySql = 0,
SqlServer = 1,
Sqlite = 2,
Oracle = 3,
PostgreSQL = 4,
Dm = 5,
Kdbndp = 6
*/
{
"Id": 1, // 连接id可以配置到数据库
"DBType": 2, // db类型枚举具体的看上边
"Enabled": false, // 是否开启当前数据库db
"Connection": "WMBlog.db" // 连接字符串
},
{
//目前使用的数据库
"Id": "118_3310_ewide",
"DBType": 0,
"Enabled": true,
"ConnectionString": "Data Source=118.178.224.202;Port=3310;Database=ewide;User ID=root;Password=root.Ewide;pooling=true;sslmode=none;CharSet=utf8;"
},
{
//郑总的线上测试数据库
"Id": "zhengzong_testdb",
"DBType": 0,
"Enabled": true,
"ConnectionString": "Data Source=42.192.248.196;Port=3306;Database=roadflow;User ID=joy;Password=db2202;pooling=true;sslmode=none;CharSet=utf8;"
},
{
//118上合并roadflow之前的数据库
"Id": "118_3306_old_ewide",
"DBType": 0,
"Enabled": true,
"ConnectionString": "Data Source=118.178.224.202;Port=3306;Database=ewide;User ID=root;Password=root;pooling=true;sslmode=none;CharSet=utf8;"
},
{
//不知道干什么用的
"Id": "PgSqlConnection",
"DBType": 4,
"Enabled": true,
"ConnectionString": "HOST=127.0.0.1;PORT=5432;DATABASE=ewide;PASSWORD=postgres;USER ID=postgres;"
},
{
"Id": "MultiTenantConnection",
"DBType": 2,
"Enabled": true,
"ConnectionString": "Data Source=./Dilon_SaaS.db"
}
]
}

View File

@@ -0,0 +1,56 @@
{
//DefaultConnection这个节点不能删
"DefaultConnection": "",
"ConnectionStrings": [
/*
MySql = 0,
SqlServer = 1,
Sqlite = 2,
Oracle = 3,
PostgreSQL = 4,
Dm = 5,
Kdbndp = 6
*/
{
"Id": 1, // 连接id可以配置到数据库
"DBType": 2, // db类型枚举具体的看上边
"Enabled": false, // 是否开启当前数据库db
"Connection": "WMBlog.db" // 连接字符串
},
{
//目前使用的数据库
"Id": "118_3310_ewide",
"DBType": 0,
"Enabled": true,
"ConnectionString": "Data Source=118.178.224.202;Port=3310;Database=ewide;User ID=root;Password=root.Ewide;pooling=true;sslmode=none;CharSet=utf8;"
},
{
//郑总的线上测试数据库
"Id": "zhengzong_testdb",
"DBType": 0,
"Enabled": true,
"ConnectionString": "Data Source=42.192.248.196;Port=3306;Database=roadflow;User ID=joy;Password=db2202;pooling=true;sslmode=none;CharSet=utf8;"
},
{
//118上合并roadflow之前的数据库
"Id": "118_3306_old_ewide",
"DBType": 0,
"Enabled": true,
"ConnectionString": "Data Source=118.178.224.202;Port=3306;Database=ewide;User ID=root;Password=root;pooling=true;sslmode=none;CharSet=utf8;"
},
{
//不知道干什么用的
"Id": "PgSqlConnection",
"DBType": 4,
"Enabled": true,
"ConnectionString": "HOST=127.0.0.1;PORT=5432;DATABASE=ewide;PASSWORD=postgres;USER ID=postgres;"
},
{
"Id": "MultiTenantConnection",
"DBType": 2,
"Enabled": true,
"ConnectionString": "Data Source=./Dilon_SaaS.db"
}
]
}