如何在 ASP.NET Core 2.1 中使用 IDesignTimeDbContextFactory 实现? [英] How to use IDesignTimeDbContextFactory implementation in ASP.NET Core 2.1?
问题描述
我有 ASP.NET Core 1.1 项目,我正在尝试将其转换为 v2.1.我找到了 IDesignTimeDbContextFactory
实现,但我不明白我应该在哪里创建这个工厂的实例以及如何使用它进行正常工作的迁移.现在在创建/删除迁移之前,我必须清理并重建解决方案,因为如果没有,我将收到以下消息:无法创建MyDbContext"类型的对象.添加 'IDesignTimeDbContextFactory
.所有上下文数据都在单独的项目中.如何使用 IDesignTimeDbContextFactory
实现或者我做错了什么?
I have ASP.NET Core 1.1 project, which I'm trying to convert to v2.1. I've found IDesignTimeDbContextFactory
implementation, but I don't understand where I should create the instance of this factory and how to use it for migrations normal working. Now before create/remove migration I must clean and rebuild solution, because if not, I will get this message: 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
. All context data is in separated project. How to use IDesignTimeDbContextFactory
implementation or what am I doing wrong?
推荐答案
将此类添加到您拥有 DbContext 的文件夹中.
Add this class to folder where you have your 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);
}
}
这篇关于如何在 ASP.NET Core 2.1 中使用 IDesignTimeDbContextFactory 实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!