实体框架核心迁移不能与类库一起使用吗?

Pas*_*cal 1 entity-framework-core asp.net-core-2.0 entity-framework-migrations

我有一个 ASP.NET 核心项目“Api”,其目标是:

<TargetFramework>net471</TargetFramework>
Run Code Online (Sandbox Code Playgroud)

该项目引用另一个类库项目“Repository”,目标为:

<TargetFramework>netstandard1.4</TargetFramework>
Run Code Online (Sandbox Code Playgroud)

“Api”项目的配置如下:

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

当我在 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
Run Code Online (Sandbox Code Playgroud)

我有什么错吗?

Chr*_*att 5

EF Core 命令仅适用于启动项目,即可以实际运行的项目,而不是类库。这是因为上下文是通过依赖注入创建的,这只能在运行时发生。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);
    }
}
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅文档