问题描述
我的 ASP.NET 核心有这个类,它首先被调用
My ASP.NET core has this class which gets called first
public class Startup
{
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<IssuerContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddMvc();
}
我的上下文是这样的:
public class IssuerContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var connString = "Server=(localdb)\mssqllocaldb;Database=HavenServer;ConnectRetryCount=0;Trusted_Connection=True;MultipleActiveResultSets=true"";
optionsBuilder
.UseLoggerFactory(MyConsoleLoggerFactory)
.EnableSensitiveDataLogging(false)
.UseSqlServer(connString, options => options.MaxBatchSize(150));
base.OnConfiguring(optionsBuilder);
}
在两个位置定义看似重叠的选项时,预期的 SQLServer 选项配置是什么?
What is the expected SQLServer options configuration when seemingly overlapping options are defined in two locations?
推荐答案
在 配置 DbContext 文档部分:
DbContextOptions
可以通过覆盖 OnConfiguring
方法或通过构造函数参数从外部提供给 DbContext
.
如果两者都使用,OnConfiguring
最后应用并且可以覆盖提供给构造函数参数的选项.
If both are used, OnConfiguring
is applied last and can overwrite options supplied to the constructor argument.
通常,在您的 OnConfiguring
覆盖中,您应该检查 DbContextOptionsBuilder.IsConfigured
属性:
In general, inside your OnConfiguring
override you are supposed to check DbContextOptionsBuilder.IsConfigured
property:
获取一个值,该值指示是否已配置任何选项.
当您覆盖 OnConfiguring
以配置上下文时,这会很有用,但在某些情况下,您还可以通过上下文构造函数从外部提供选项.此属性可用于确定选项是否已设置,并跳过 OnConfiguring
中的部分或全部逻辑.
This can be useful when you have overridden OnConfiguring
to configure the context, but in some cases you also externally provide options via the context constructor. This property can be used to determine if the options have already been set, and skip some or all of the logic in OnConfiguring
.
例如
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
var connString = "Server=(localdb)\mssqllocaldb;Database=HavenServer;ConnectRetryCount=0;Trusted_Connection=True;MultipleActiveResultSets=true"";
optionsBuilder
.UseLoggerFactory(MyConsoleLoggerFactory)
.EnableSensitiveDataLogging(false)
.UseSqlServer(connString, options => options.MaxBatchSize(150));
}
base.OnConfiguring(optionsBuilder);
}
这篇关于在 DbContext.OnConfiguring 和 AspCore Startup.ConfigureServices 中定义 optionsBuilder 时,预期结果是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!