我正在尝试从另一个.NET Core项目添加ApiAuthorizationDbContext
的迁移,但是由于我不知道如何获取第二个参数IOptions<OperationalStoreOptions>
,所以无法在设计时实例化它。
这是我的DbContext构造函数(继承了我的自定义ApiAuthorizationDbContext
,它接受TUser,TRole和TKey)
public class ApplicationDbContext : ApiAuthorizationDbContext<ApplicationUser, ApplicationRole, Guid>
{
public ApplicationDbContext (DbContextOptions options, IOptions<OperationalStoreOptions> operationalStoreOptions)
: base(options, operationalStoreOptions)
{
}
这是我的DesignTimeDbContextFactory
public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<KontestDbContext>
{
public ApplicationDbContext CreateDbContext(string[] args)
{
IConfiguration configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json").Build();
var builder = new DbContextOptionsBuilder<ApplicationDbContext>();
var connectionString = configuration.GetConnectionString("DefaultConnection");
builder.UseSqlServer(connectionString);
return new ApplicationDbContext(builder.Options, ????); <--- how to resolve the IOptions<OperationStoreOptions> here ??
}
}
我从this issue in GitHub找到了答案,但仍然找不到解决该参数的方法。
我还尝试将IOptions <>注入构造函数,但是在添加迁移时,它抛出一个异常,即找不到DesignTimeDbContextFactory的无参数构造函数
有人可以给我一个提示吗,我在这里对.NET Core / EF Core还是很陌生,如果有人可以提供帮助,我将非常感谢!
(我正在使用.NET Core 3.0和Entity Framework Core)
答案 0 :(得分:2)
继承 IOptions 创建 OperationalStoreOptionsMigrations ,并传递 OperationalStoreOptionsMigrations 对象。 看看我的答案。
创建 OperationalStoreOptionsMigrations 方法。
public class OperationalStoreOptionsMigrations :
IOptions<OperationalStoreOptions>
{
public OperationalStoreOptions Value => new OperationalStoreOptions()
{
DeviceFlowCodes = new TableConfiguration("DeviceCodes"),
EnableTokenCleanup = false,
PersistedGrants = new TableConfiguration("PersistedGrants"),
TokenCleanupBatchSize = 100,
TokenCleanupInterval = 3600,
};
}
更改 DesignTimeDbContextFactory
public class DesignTimeDbContextFactory :
IDesignTimeDbContextFactory<KontestDbContext>
{
public ApplicationDbContext CreateDbContext(string[] args)
{
IConfiguration configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json").Build();
var builder = new DbContextOptionsBuilder<ApplicationDbContext>();
var connectionString =
configuration.GetConnectionString("DefaultConnection");
builder.UseSqlServer(connectionString);
return new ApplicationDbContext(builder.Options, new OperationalStoreOptionsMigrations());
}
}
答案 1 :(得分:0)
在构造函数中将IOptions<OprerationalStoreOption>
作为参数传递,然后可以在需要的地方使用它。然后在IOptions
容器中注册DI
服务。像这样
public ApplicationDbContext CreateDbContext(string[] args, Options<OperationStoreOptions> optionsBuilder)
{
IConfiguration configuration = new ConfigurationBuilder()
return new ApplicationDbContext(builder.Options, optionsBuilder);
}