我有一个asp.net核心项目'Api',其目标是:
<TargetFramework>net471</TargetFramework>
该项目引用另一个带有目标的
类库项目'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
我错了什么?
答案 0 :(得分:0)
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);
}
}
有关详细信息,请参阅documentation。