codeFirst实体建表

This commit is contained in:
不做码农 2023-06-09 18:10:38 +08:00
parent b96edfdac7
commit 1af7e778af
8 changed files with 33 additions and 43 deletions

View File

@ -1,7 +1,5 @@
using Infrastructure; using Infrastructure;
using Infrastructure.Attribute; using Infrastructure.Attribute;
using Microsoft.Extensions.DependencyInjection;
using System.Linq;
using System.Reflection; using System.Reflection;
namespace ZR.Admin.WebApi.Extensions namespace ZR.Admin.WebApi.Extensions

View File

@ -24,16 +24,14 @@ namespace ZR.Admin.WebApi.Extensions
//仅本人数据权限 //仅本人数据权限
public static long DATA_SCOPE_SELF = 5; public static long DATA_SCOPE_SELF = 5;
private static XmlCommentHelper commentHelper = new XmlCommentHelper();
/// <summary> /// <summary>
/// 初始化db /// 初始化db
/// </summary> /// </summary>
/// <param name="services"></param> /// <param name="services"></param>
/// <param name="Configuration"></param> /// <param name="Configuration"></param>
public static void AddDb(this IServiceCollection services, IConfiguration Configuration) /// <param name="environment"></param>
public static void AddDb(this IServiceCollection services, IConfiguration Configuration, IWebHostEnvironment environment)
{ {
commentHelper.LoadAll();
List<DbConfigs> dbConfigs = Configuration.GetSection("DbConfigs").Get<List<DbConfigs>>(); List<DbConfigs> dbConfigs = Configuration.GetSection("DbConfigs").Get<List<DbConfigs>>();
var iocList = new List<IocConfig>(); var iocList = new List<IocConfig>();
@ -64,6 +62,11 @@ namespace ZR.Admin.WebApi.Extensions
SetSugarAop(db, iocConfig, cache); SetSugarAop(db, iocConfig, cache);
}); });
}); });
if(Configuration["InitDb"].ParseToBool() == true && environment.IsDevelopment())
{
InitDb();
}
} }
/// <summary> /// <summary>
@ -74,8 +77,8 @@ namespace ZR.Admin.WebApi.Extensions
/// <param name="cache"></param> /// <param name="cache"></param>
private static void SetSugarAop(SqlSugarClient db, IocConfig iocConfig, ICacheService cache) private static void SetSugarAop(SqlSugarClient db, IocConfig iocConfig, ICacheService cache)
{ {
var config = db.GetConnection(iocConfig.ConfigId).CurrentConnectionConfig; var config = db.GetConnectionScope(iocConfig.ConfigId).CurrentConnectionConfig;
string configId = config.ConfigId; string configId = config.ConfigId;
db.GetConnectionScope(configId).Aop.OnLogExecuting = (sql, pars) => db.GetConnectionScope(configId).Aop.OnLogExecuting = (sql, pars) =>
{ {
@ -107,6 +110,9 @@ namespace ZR.Admin.WebApi.Extensions
logger.Error(ex, $"{sql}\r\n{ex.Message}\r\n{ex.StackTrace}"); logger.Error(ex, $"{sql}\r\n{ex.Message}\r\n{ex.StackTrace}");
}; };
db.GetConnectionScope(configId).Aop.DataExecuting = (oldValue, entiyInfo) =>
{
};
db.GetConnectionScope(configId).CurrentConnectionConfig.MoreSettings = new ConnMoreSettings() db.GetConnectionScope(configId).CurrentConnectionConfig.MoreSettings = new ConnMoreSettings()
{ {
IsAutoRemoveDataCache = true IsAutoRemoveDataCache = true
@ -118,11 +124,6 @@ namespace ZR.Admin.WebApi.Extensions
{ {
p.DbTableName = p.DbTableName.FirstLowerCase(); p.DbTableName = p.DbTableName.FirstLowerCase();
p.DbColumnName = p.DbColumnName.FirstLowerCase(); p.DbColumnName = p.DbColumnName.FirstLowerCase();
var des = commentHelper.GetFieldOrPropertyComment(c);
if (des.IsNotEmpty())
{
p.ColumnDescription = des;
}
if (db.GetConnectionScope(configId).CurrentConnectionConfig.DbType == DbType.PostgreSQL) if (db.GetConnectionScope(configId).CurrentConnectionConfig.DbType == DbType.PostgreSQL)
{ {
@ -149,26 +150,20 @@ namespace ZR.Admin.WebApi.Extensions
} }
} }
}; };
db.GetConnectionScope(configId).Aop.DataExecuting = (oldValue, entiyInfo) =>
{
};
} }
/// <summary> /// <summary>
/// 创建db、表 /// 创建db、表
/// </summary> /// </summary>
/// <param name="service"></param> public static void InitDb()
public static void InitDb(this IServiceProvider service)
{ {
var db = DbScoped.SugarScope; var db = DbScoped.SugarScope;
//建库:如果不存在创建数据库存在不会重复创建 //建库:如果不存在创建数据库存在不会重复创建
db.DbMaintenance.CreateDatabase();// 注意 Oracle和个别国产库需不支持该方法需要手动建库 db.DbMaintenance.CreateDatabase();// 注意 Oracle和个别国产库需不支持该方法需要手动建库
var baseType = typeof(SysBase); var baseType = typeof(SysBase);
var entityes = AssemblyUtils.GetAllTypes().Where(p => !p.IsAbstract && p != baseType && /*p.IsAssignableTo(baseType) && */p.GetCustomAttribute<SugarTable>() != null).ToArray(); var entityes = AssemblyUtils.GetAllTypes().Where(p => !p.IsAbstract && p != baseType && p.GetCustomAttribute<SugarTable>() != null).ToArray();
//23个表 //23个表
db.CodeFirst.InitTables(entityes); db.CodeFirst.InitTables(entityes);
} }

View File

@ -2,6 +2,7 @@
using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.Filters; using Swashbuckle.AspNetCore.Filters;
using System.Reflection;
namespace ZR.Admin.WebApi.Extensions namespace ZR.Admin.WebApi.Extensions
{ {
@ -52,9 +53,12 @@ namespace ZR.Admin.WebApi.Extensions
{ {
//var tempPath = hostEnvironment.ContentRootPath; //var tempPath = hostEnvironment.ContentRootPath;
//添加文档注释 //添加文档注释
c.IncludeXmlComments(Path.Combine("ZRAdmin.xml"), true); var baseDir = AppContext.BaseDirectory;
c.IncludeXmlComments(Path.Combine("ZRModel.xml"), true); c.IncludeXmlComments(Path.Combine(baseDir, "ZR.Model.xml"), true);
//c.IncludeXmlComments(Path.Combine(Directory.GetParent(tempPath).FullName, "ZR.Model", "ZRModel.xml"), true);
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(baseDir, xmlFile);
c.IncludeXmlComments(xmlPath);
} }
catch (Exception ex) catch (Exception ex)
{ {

View File

@ -1,15 +1,14 @@
using AspNetCoreRateLimit;
using Infrastructure; using Infrastructure;
using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.DataProtection;
using ZR.Admin.WebApi.Framework; using Microsoft.IdentityModel.Tokens;
using Infrastructure.Extensions;
using ZR.Admin.WebApi.Extensions; using ZR.Admin.WebApi.Extensions;
using ZR.Admin.WebApi.Filters; using ZR.Admin.WebApi.Filters;
using ZR.Admin.WebApi.Middleware; using ZR.Admin.WebApi.Framework;
using ZR.Admin.WebApi.Hubs; using ZR.Admin.WebApi.Hubs;
using ZR.Admin.WebApi.Middleware;
using ZR.Common.Cache; using ZR.Common.Cache;
using AspNetCoreRateLimit;
using Microsoft.IdentityModel.Tokens;
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
@ -68,8 +67,6 @@ builder.Services.AddSingleton(new AppSettings(builder.Configuration));
builder.Services.AddAppService(); builder.Services.AddAppService();
//开启计划任务 //开启计划任务
builder.Services.AddTaskSchedulers(); builder.Services.AddTaskSchedulers();
//初始化db
builder.Services.AddDb(builder.Configuration);
//注册REDIS 服务 //注册REDIS 服务
var openRedis = builder.Configuration["RedisServer:open"]; var openRedis = builder.Configuration["RedisServer:open"];
@ -92,10 +89,8 @@ builder.Services.AddSwaggerConfig();
var app = builder.Build(); var app = builder.Build();
InternalApp.ServiceProvider = app.Services; InternalApp.ServiceProvider = app.Services;
if (builder.Configuration["InitDb"].ParseToBool() == true && app.Environment.IsDevelopment()) //初始化db
{ builder.Services.AddDb(builder.Configuration, app.Environment);
app.Services.InitDb();
}
app.UseSwagger(); app.UseSwagger();

View File

@ -3,10 +3,9 @@
<TargetFramework>net7.0</TargetFramework> <TargetFramework>net7.0</TargetFramework>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<GenerateDocumentationFile>True</GenerateDocumentationFile> <GenerateDocumentationFile>true</GenerateDocumentationFile>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DocumentationFile>ZRAdmin.xml</DocumentationFile>
<NoWarn>1701;1702;1591,8603,8602,8604,8600</NoWarn> <NoWarn>1701;1702;1591,8603,8602,8604,8600</NoWarn>
</PropertyGroup> </PropertyGroup>

View File

@ -12,6 +12,6 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="JinianNet.JNTemplate" Version="2.3.3" /> <PackageReference Include="JinianNet.JNTemplate" Version="2.3.3" />
<PackageReference Include="SqlSugarCoreNoDrive" Version="5.1.4.84-preview01" /> <PackageReference Include="SqlSugarCoreNoDrive" Version="5.1.4.84-preview08" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@ -2,15 +2,14 @@
<PropertyGroup> <PropertyGroup>
<TargetFramework>net7.0</TargetFramework> <TargetFramework>net7.0</TargetFramework>
<GenerateDocumentationFile>True</GenerateDocumentationFile> <GenerateDocumentationFile>true</GenerateDocumentationFile>
<DocumentationFile>../ZR.Admin.WebApi/ZRModel.xml</DocumentationFile>
<NoWarn>1701;1702;1591;1570</NoWarn> <NoWarn>1701;1702;1591;1570</NoWarn>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="MiniExcel" Version="1.30.3" /> <PackageReference Include="MiniExcel" Version="1.30.3" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.2" /> <PackageReference Include="Newtonsoft.Json" Version="13.0.2" />
<PackageReference Include="SqlSugarCoreNoDrive" Version="5.1.4.84-preview01" /> <PackageReference Include="SqlSugarCoreNoDrive" Version="5.1.4.84-preview08" />
<PackageReference Include="System.ComponentModel.Annotations" Version="5.0.0" /> <PackageReference Include="System.ComponentModel.Annotations" Version="5.0.0" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@ -15,6 +15,6 @@
<PackageReference Include="MySqlConnector" Version="2.2.6" /> <PackageReference Include="MySqlConnector" Version="2.2.6" />
<PackageReference Include="NETCore.Encrypt" Version="2.1.1" /> <PackageReference Include="NETCore.Encrypt" Version="2.1.1" />
<PackageReference Include="SqlSugar.IOC" Version="2.0.0" /> <PackageReference Include="SqlSugar.IOC" Version="2.0.0" />
<PackageReference Include="SqlSugarCoreNoDrive" Version="5.1.4.84-preview01" /> <PackageReference Include="SqlSugarCoreNoDrive" Version="5.1.4.84-preview08" />
</ItemGroup> </ItemGroup>
</Project> </Project>