EntityFrameworkInstaller.cs 1.43 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)
        {
            appDbContext.EnsureDatabaseCreated();
        }
    }
}