我尝试在控制台.net core 2.0应用程序中使用EF Core 2.0。当我使用IDesignTimeDbContextFactory
或覆盖OnConfiguring
派生类DbContext
的{{1}}方法时,CustomerDbContext
在包管理器控制台中成功。但是如果我尝试在asp.net核心应用程序中使用Add-Migration
,我会收到消息:
AddDbContext
控制台.net核心应用程序的代码段是:
Unable to create an object of type 'CustomerDbContext'
class Program
{
static void Main(string[] args)
{
var services = new ServiceCollection();
IConfigurationRoot config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("config.json") //needs Microsoft.Extensions.Configuration.Json
.Build();
string conn = config.GetConnectionString("WarehouseConnection");
services
.AddDbContext<CustomerDbContext>(
options => options.UseSqlServer(config.GetConnectionString("WarehouseConnection")));
var provider = services.BuildServiceProvider();
using(var context = provider.GetService<CustomerDbContext>())
{
...
}
}
}
包含连接字符串:
config.json
{
"ConnectionStrings": {
"WarehouseConnection": "Server=(localdb)\\mssqllocaldb;Database=WAREHOUSE;Trusted_Connection=True;MultipleActiveResultSets=true"
}
类是:
CustomerDbContext
为什么这种方法失败的任何想法?
答案 0 :(得分:2)
从2.0开始,EF工具检查z-index: 1;
方法并使用它来访问应用程序服务(如果它存在)。由于您不需要BuildWebHost()
使用BuildWebHost()
是正确的做法。
答案 1 :(得分:1)
所以你需要实现IDesignTimeDbContextFactory
接口。在项目中添加一个实现此接口的类。
public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<AppDbContext>
{
public CustomerDbContext CreateDbContext(string[] args)
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
var builder = new DbContextOptionsBuilder<CustomerDbContext>();
var connectionString = configuration.GetConnectionString("WarehouseConnection");
builder.UseSqlServer(connectionString);
return new CustomerDbContext(builder.Options);
}
}
有关详细信息,请参阅Cannot make migration. ef core 2.0