添加迁移失败,在控制台核心2.0应用程序

时间:2017-12-08 11:42:26

标签: c# .net-core entity-framework-core

我尝试在控制台.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

为什么这种方法失败的任何想法?

2 个答案:

答案 0 :(得分:2)

从2.0开始,EF工具检查z-index: 1; 方法并使用它来访问应用程序服务(如果它存在)。由于您不需要BuildWebHost()使用BuildWebHost()是正确的做法。

检查the announcementthis comment in the discussion以获取更多信息。

答案 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