entity framework 核心迁移不适用于 class 库,但是吗?

entity framework core migrations do not work with class library, yet?

我有一个 asp.net 核心项目 'Api' 目标:

<TargetFramework>net471</TargetFramework>

该项目引用了另一个 class 库项目 'Repository',目标为:

<TargetFramework>netstandard1.4</TargetFramework>

'Api' 项目配置如下:

services
.AddEntityFrameworkSqlServer()
.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
    b => b.MigrationsAssembly("Repository"))
)
.AddScoped(p => new ApplicationDbContext(p.GetService<DbContextOptions<ApplicationDbContext>>()));

当我在 PMConsole 中输入:

添加迁移初始

然后我得到这个错误:

Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[0]
add-migration : Exception calling "Substring" with "1" argument(s): "StartIndex cannot be less than zero.
Parameter name: startIndex"
At line:1 char:1
+ add-migration
+ ~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Add-Migration], MethodInvocationException
    + FullyQualifiedErrorId : ArgumentOutOfRangeException,Add-Migration

我做错了什么?

EF Core 命令仅适用于启动项目,即实际上可以 运行 的东西,而不是 class 库。这是因为上下文是通过依赖注入创建的,这只能在 运行 时间内发生。解决方法是在 class 库中创建 IDesignTimeDbContextFactory 的实现。当命令看到您的实现时,该工厂将用于实例化上下文。

public class MyContextFactory : IDesignTimeDbContextFactory<MyContext>
{
    public MyContext CreateDbContext(string[] args)
    {
        var optionsBuilder = new DbContextOptionsBuilder<MyContext>();
        optionsBuilder.UseSqlServer("[connection string here]");

        return new MyContext(optionsBuilder.Options);
    }
}

有关详细信息,请参阅 documentation