C# 在DbContext.onconfig和AspCore Startup.ConfigureServices中定义OptionBuilder时,预期的结果是什么?
我的ASP.NET核心有一个首先被调用的类C# 在DbContext.onconfig和AspCore Startup.ConfigureServices中定义OptionBuilder时,预期的结果是什么?,c#,asp.net-core,entity-framework-core,C#,Asp.net Core,Entity Framework Core,我的ASP.NET核心有一个首先被调用的类 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 serv
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();
}
当在两个位置定义看似重叠的选项时,SQLServer选项的预期配置是什么 通常,这两个选项都将应用于“onconfigurang”方法中的配置,而“ConfigureServices”方法中的配置是“除配置之外应用的”。ConfigureServices用于为DbContext设置依赖项注入,因此它将使用这些选项作为构造函数参数。在OnConfigurang方法中完成的任何其他配置都将附加或覆盖StartUp类中的配置。但是,在您提供的示例中,DbContext中没有构造函数,因此不会使用Startup类中的配置 文档部分对此进行了解释:
DbContextOptions
可以通过重写onconfig
方法或通过构造函数参数从外部提供给DbContext
如果两者都使用,onconfigurang
将最后应用,并且可以覆盖提供给构造函数参数的选项
通常,在配置的覆盖中,您应该检查属性:
获取一个值,该值指示是否已配置任何选项
当您已覆盖onconfigurang
以配置上下文时,这可能非常有用,但在某些情况下,您还可以通过上下文构造函数从外部提供选项。此属性可用于确定选项是否已设置,并跳过配置中的部分或全部逻辑
例如
似乎DbContextOptionsBuilder.IsConfigured
始终为false,即使通过services.AddDbContext
在Startup.cs中使用。有什么想法吗?@Yahia如果AddDbContext
包含选项,则返回true
。请使用SQLServer(…)
或类似选项。谢谢。是DI在db上下文中选择了错误的额外构造函数的问题。@Yahia您是如何纠正的?
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);
}
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);
}