IHostingEnvironment如何传递OnModelCreating?

时间:2018-06-18 19:12:24

标签: entity-framework-core asp.net-core-2.1

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

1 个答案:

答案 0 :(得分:0)

如果您要使用外部“初始化程序”类(至少在ASP.NET核心应用程序的上下文中),您可能会这样做:

DbContext类:

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) {
        //...
    }
}

初始化程序类:

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
}

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