IHostingEnvironment如何传递给OnModelCreating?

IHostingEnvironment how to pass OnModelCreating?

我想创建一些将从 json 文件加载的虚拟数据。我需要获取文件的路径,根据我的研究我发现我需要 IHostingEnvironment 但我不确定如何在我的 DbContext class 文件中获取 属性。

如果您要使用外部 "Initializer" class(至少在 ASP.NET 核心应用程序的上下文中),您可能会做这样的事情:

DbContext class:

public class SampleDbContext : Microsoft.EntityFrameworkCore.DbContext {
    public SampleDbContext(DbContextOptions<SampleDbContext> options) : base(options) { }

    public DbSet<SampleRecord> SampleRecords { get; set; }

    //...Other DB structure here

    protected override void OnModelCreating(ModelBuilder modelBuilder) {
        //...
    }
}

初始化器class:

public static void Initialize(SampleDbContext context, var JSONStringOrObj) {
    context.Database.EnsureCreated();

    //Data seeding sample
    if(!context.SampleRecords.Any()) {
        context.SampleTable.AddRange(new SampleTable[]
        {
            new SampleRecord() { SampleData = "Test1" },
            new SampleRecord() { SampleData = "Test2" },
            new SampleRecord() { SampleData = "Test3" },
            new SampleRecord() { SampleData = "Test4" }
        });
    }

    //Extract seed data from JSON and add to proper DbSet ...

    context.SaveChanges();
}

Startup.cs:

public class Startup {

    public IHostingEnvironment HostingEnvironment { get; }

    public Startup(IHostingEnvironment env) {
        //...

        HostingEnvironment = env;

        //...
    }

    public void ConfigureServices(IServiceCollection services) {
        //...

        services.AddDbContext<SampleDbContext>(/*Your options here*/);

        services.AddSingleton<IHostingEnvironment>(HostingEnvironment);

        //...
    }

    //... Rest of class
}

Program.cs:

public class Program {
    public static void Main(string[] args) {
        var host = CreateWebHostBuilder(args).Build()

        using (var scope = host.Services.CreateScope()) {
            var services = scope.ServiceProvider;
            var hostingEnvironment = services.GetService<IHostingEnvironment>();

            //... do whatever you need to get your JSON file here (var jsonData = ...)

            var sampleDbContext = services.GetService<SampleDbContext>();
            Initializer.Initialize(sampleDbContext, jsonData);
        }

        host.Run();
    }

    //... Rest of class
}

种子数据将与您的架构分开,并在您的应用运行时加载到数据库中。您还可以从测试代码中调用初始化程序(如果您想将特定的测试数据放入测试中,则不调用)。