use*_*566 0 seeding entity-framework-core asp.net-core-mvc
我正在 ApplicationDbContext.cs 的 OnModelCreating 方法中播种数据。我想总是添加一些数据,但也有条件地添加一些数据(仅当环境是开发时)。
我怎样才能做到这一点?我无法将方法签名更改为具有“IHostingEnvironment env”,因为在这种情况下它不会覆盖 OnModelCreating。
protected override void OnModelCreating(ModelBuilder builder)
谢谢!
DbContext有一个内部服务提供商可供您利用:
var env = this.GetService<IHostingEnvironment>();
if (env.IsDevelopment())
{
    // seed
}
您需要services.AddDbContext稍微修改一下:
services.AddDbContext<MyContext>(o => o
    .UseSqlServer(Configuration.GetConnectionString("Default"))
    .UseInternalServiceProvider());
| 归档时间: | 
 | 
| 查看次数: | 850 次 | 
| 最近记录: |