Reputation: 12855
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?
Upvotes: 1
Views: 2958
Reputation: 239200
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.
Upvotes: 5