EntityFrameworkInstaller.cs 1.75 KB
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();
        }
    }
}