EntityFrameworkInstaller.cs
1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
using System.Linq;
using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Npgsql;
using Rcs.Domain.Settings;
using Rcs.Infrastructure.DB.MsSql;
namespace Rcs.Infrastructure.Installs
{
public static class EntityFrameworkInstaller
{
public static void InstallEntityFramework(this WebApplicationBuilder builder)
{
var appSettings = builder.Configuration.GetSection(nameof(AppSettings)).Get<AppSettings>();
if (appSettings != null)
{
var msSqlSettings = appSettings.ConnSql;
builder.Services.AddDbContext<AppDbContext>(options =>
{
options.UseNpgsql(msSqlSettings.ConnectionString, o => o.UseNetTopologySuite());
// 禁用 SQL 查询语句日志
options.ConfigureWarnings(warnings => warnings
.Ignore(RelationalEventId.CommandExecuting)
.Ignore(RelationalEventId.CommandExecuted));
});
builder.Services.AddScoped<IAppDbContext>(provider => provider.GetService<AppDbContext>());
}
}
public static void SeedDatabase(AppDbContext appDbContext)
{
// 使用 EnsureCreated() 直接根据模型创建数据库结构
// 适用于没有迁移文件的情况
// 注意:EnsureCreated() 不会应用迁移,如果数据库已存在则不会更新结构
// 如果需要支持模型变更,应该使用 Migrate() 配合迁移文件
appDbContext.Database.EnsureCreated();
}
}
}