我有ASP.NET Core 1.1项目,我试图转换为v2.1。我发现IDesignTimeDbContextFactory
已实施,但我不知道应该在哪里创建此工厂的实例,以及如何将其用于正常工作的迁移。现在在创建/删除迁移之前,我必须清理并重建解决方案,因为如果没有,我将收到此消息:Unable to create an object of type 'MyDbContext'. Add an implementation of 'IDesignTimeDbContextFactory<MyDbContext>' to the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time
。所有上下文数据都在分离的项目中。如何使用IDesignTimeDbContextFactory
实现或我做错了什么?
答案 0 :(得分:3)
将此类添加到具有DbContext的文件夹中。
public class MyDbContextFactory : IDesignTimeDbContextFactory<MyDbContext>
{
MyDbContext IDesignTimeDbContextFactory<MyDbContext>.CreateDbContext(string[] args)
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
var builder = new DbContextOptionsBuilder<MyDbContext>();
var connectionString = configuration.GetConnectionString("DefaultConnection");
builder.UseSqlServer(connectionString);
return new MyDbContext(builder.Options);
}
}