c# - Entity Framework Core 2.1 中特定环境的播种数据

标签 c# asp.net-core entity-framework-core

我在 EF Core 2.1 中使用新的数据播种方式,我只想为开发环境播种数据。

最初我试过这个:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    if (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") != EnvironmentName.Development)
    {
        return;
    }

    modelBuilder.Entity<Customer>().HasData(new Customer { ... });
}

但是,我注意到生成的迁移总是会将客户插入到数据库中。

有没有办法在每个环境的基础上限制数据种子?

最佳答案

这有点老了,但我所做的是创建扩展方法以从 Startup.cs 调用,并根据数据库是否存在来为它做种子。我还将那个电话包装在一个环境中 如果数据库已经存在,则不会进行数据库播种,但是,我相信这种行为很好,因为数据库已经存在,您很可能不在开发环境中。

public static class Extensions
{
    public static void UseDbSeeding(this IApplicationBuilder app)
    {
        var factory = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>();
        using var serviceScope = factory.CreateScope();
        var context = serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
        if(context.Database.EnsureCreated()) // false when db already exists
        {
            // Seed here
            context.SaveChanges();
        }
    }
}

来自Startup.cs

public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 
{
    if (env.IsDevelopment())
    {
        app.UseDbSeeding();
    }
}

关于c# - Entity Framework Core 2.1 中特定环境的播种数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51026744/

相关文章:

c# - F# 和 C# 中 COM 对象创建的差异

c# - 静态与动态控制 + 基于情境

时间:2019-03-09 标签:c#graphicswpf

c# - 为什么 Guid.ToByteArray() 按照它的方式对字节进行排序?

ajax - 我可以通过 ajax 重新加载 asp 5/MVC 6 View 组件吗?

c# - 为什么 Application Insights 依赖关系时间线存在间隙?

c# - 带 id 的默认路由在 ASP.NET Core 中不起作用

entity-framework-core - Entity Framework Core 1.0 代码优先迁移使用代码?

c# - AspNet Identity - 重复外键的自定义 IdentityRoleClaim 和 IdentityUserRole 和 IdentityUserClaim

entity-framework-core - Entity Framework Core 更新未更改的字段