在 .NET core 2.0 中创建迁移步骤时向项目错误添加 'IDesignTimeDbContextFactory<ServicesDbContext>' 的实现

Add an implementation of 'IDesignTimeDbContextFactory<ServicesDbContext>' to the project error while creating a migration step in .NET core 2.0

我有一个 .NET core 1.0 webapp 运行良好。我不得不升级到 .NET Core 2.0。我还必须为我的 SQLite 数据库添加一个迁移步骤。

如果我启动这个命令:

Add-Migration MyMigrationStepName

我收到这个错误:

Unable to create an object of type 'ServicesDbContext'. Add an implementation of 'IDesignTimeDbContextFactory' to the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time.

我在 SO 和其他博客和网站上看到了很多答案,但是 none 实际上说了在哪里实现这样的接口以及具体方法应该包含什么代码!

示例:

public class ApplicationDbContext : IdentityDbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { }
}

public class ApplicationContextDbFactory : IDesignTimeDbContextFactory<ApplicationDbContext>
{
    ApplicationDbContext IDesignTimeDbContextFactory<ApplicationDbContext>.CreateDbContext(string[] args)
    {
        var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
        optionsBuilder.UseSqlServer<ApplicationDbContext>("Server = (localdb)\mssqllocaldb; Database = MyDatabaseName; Trusted_Connection = True; MultipleActiveResultSets = true");

        return new ApplicationDbContext(optionsBuilder.Options);
    }
}

位置:

将 class 放在放置 ApplicationDbContext 的位置。当您使用 dotnet ef cli 命令时,它将被自动拾取。

IDesignTimeDbContextFactory<> 问题的可能解决方案是添加迁移过程中的 DBContext discovery/launch。 添加迁移需要获取上下文。如果不能,则抛出此错误。 如果您没有 public 无参数 DBContext,就会发生这种情况。 因此,一个解决方案是向您的上下文添加一个 public 无参数构造函数。

public  class SomeDbContext: DbContext
{
    // this PUBLIC constructor  is required for Migration tool
    public SomeDbContext()
    {

    }
  // the model...
    public DbSet<PocoBla> PocoBlas { get; set; }
    ....
 }

您可以在单独的项目 .netCore 控制台项目中使用特殊版本的 DBContext 来生成迁移代码。

我通过简单地将 Program.cs 更新到最新的 .NET Core 2.x 模式来解决问题:

来自 1.x:

using System.IO; using Microsoft.AspNetCore.Hosting;

namespace AspNetCoreDotNetCore1App {
    public class Program
    {
        public static void Main(string[] args)
        {
            var host = new WebHostBuilder()
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration()
                .UseStartup<Startup>()
                .UseApplicationInsights()
                .Build();

            host.Run();
        }
    } }

至2.x:

using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;

namespace AspNetCoreDotNetCore2App
{
    public class Program
    {
        public static void Main(string[] args)
        {
            BuildWebHost(args).Run();
        }

        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .Build();
    }
}

来源:https://docs.microsoft.com/en-us/ef/core/miscellaneous/cli/dbcontext-creation