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

asp.net-core-2.0 ef-migrations entity-framework-core

Question

I have an asp.net core project 'Api' with target:

<TargetFramework>net471</TargetFramework>

That project references another class library project 'Repository' with target:

<TargetFramework>netstandard1.4</TargetFramework>

The 'Api' project has this configured:

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

When I am in the PMConsole I enter:

Add-Migration Initial

then I get this error:

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

What do I wrong?

1
0
1/2/2018 11:20:05 PM

Accepted Answer

The EF Core commands only work for startup projects, i.e. something that can actually run, as opposed to a class library. This is because the context is created via dependency injection, which can only occur during runtime. A workaround is to create an implementation of IDesignTimeDbContextFactory in your class library. When the commands see your implementation, that factory will then be used to instantiate the context.

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);
    }
}

For more information, see the documentation.

1
1/3/2018 2:33:22 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow