OnModelCreating 中的环境检查

use*_*566 0 seeding entity-framework-core asp.net-core-mvc

我正在 ApplicationDbContext.cs 的 OnModelCreating 方法中播种数据。我想总是添加一些数据,但也有条件地添加一些数据(仅当环境是开发时)。

我怎样才能做到这一点?我无法将方法签名更改为具有“IHostingEnvironment env”,因为在这种情况下它不会覆盖 OnModelCreating。

protected override void OnModelCreating(ModelBuilder builder)
Run Code Online (Sandbox Code Playgroud)

谢谢!

Chr*_*att 5

DbContext有一个内部服务提供商可供您利用:

var env = this.GetService<IHostingEnvironment>();
if (env.IsDevelopment())
{
    // seed
}
Run Code Online (Sandbox Code Playgroud)

您需要services.AddDbContext稍微修改一下:

services.AddDbContext<MyContext>(o => o
    .UseSqlServer(Configuration.GetConnectionString("Default"))
    .UseInternalServiceProvider());
Run Code Online (Sandbox Code Playgroud)