我正在开发具有DLL(EF Core 2.1)中声明的DbContext的.NET CORE MVC 2.1 Web应用程序。
我想使用IServiceCollection.AddContext<GladContext
>来配置上下文,但是如果我没有 ALSO 对其进行配置DbContext.OnConfiguring(DbContextOptionsBuilder optionsBuilder)
,则会被告知尚未配置任何数据库提供程序尽管有一个构造函数使用DbContextOptions<GladContext>
public GladContext(DbContextOptions<GladContext> options, IGladConnectionStringProvider connectionStringProvider) : base(options)
{
_connectionStringProvider = connectionStringProvider;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
GladOptionsBuilderHelper.ConfigureDefaultOptionsBuilder(optionsBuilder, _connectionStringProvider.ConnectionString);
base.OnConfiguring(optionsBuilder);
}
IGladConnectionStringProvider
是我当前的解决方法,如果不是,那是可以接受的,因为我现在需要同时配置DbContextOptionsBuilder
和DbContextOptionsBuilder<GladContext>
public static class GladOptionsBuilderHelper
{
public const string GladMigrationsHistory = "__GladMigrationsHistory";
public static DbContextOptionsBuilder<GladContext> CreateDefaultTypedOptionsBuilder(string connectionString)
{
var optionsBuilder = new DbContextOptionsBuilder<GladContext>();
optionsBuilder
.UseSqlServer(connectionString, options =>
{
options.EnableRetryOnFailure();
options.MigrationsHistoryTable(GladMigrationsHistory, EntityBase.SchemaName);
})
.ConfigureWarnings(warnings => warnings.Throw(RelationalEventId.QueryClientEvaluationWarning));
return optionsBuilder;
}
public static void ConfigureDefaultOptionsBuilder(DbContextOptionsBuilder optionsBuilder, string connectionString)
{
optionsBuilder
.UseSqlServer(connectionString, options =>
{
options.EnableRetryOnFailure();
options.MigrationsHistoryTable(GladMigrationsHistory, EntityBase.SchemaName);
})
.ConfigureWarnings(warnings => warnings.Throw(RelationalEventId.QueryClientEvaluationWarning));
}
}
DbContextOptionsBuilder<GladContext>
中使用了IDesignTimeDbContextFactory<GladContext>
您能告诉我如何使用AddContext
来配置GladContext
或如何从DbContextOptionsBuilder
来构建DbContextOptionsBuilder<GladContext>
或相反吗?
答案 0 :(得分:0)
其中的配置部分是IServiceCollection.AddDbContext()的覆盖。
因此,当您调用AddDbContext时,只需将您的选项添加到括号中即可,如下所示:
var connectionString = "CONNECTION-STRING-HERE";
services.AddDbContext<MyContext>(o => o
.UseSqlServer(connectionString)
.UseQueryTrackingBehavior(true)
.EnableSensitiveDataLogging(true));
public class MyContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public MyContext(DbContextOptions<MyContext> options) : base(options)
{
}
}