gpt4 book ai didi

c# - 在 DbContext.OnConfiguring 和 AspCore Startup.ConfigureServices 中定义 optionsBuilder 时的预期结果是什么?

转载 作者:行者123 更新时间:2023-11-30 14:06:15 32 4
gpt4 key购买 nike

我的 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 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 选项配置是什么?

最佳答案

Configuring a DbContext 中有解释文档部分:

The DbContextOptions can be supplied to the DbContext by overriding the OnConfiguring method or externally via a constructor argument.

If both are used, OnConfiguring is applied last and can overwrite options supplied to the constructor argument.

一般来说,在您的 OnConfiguring 覆盖中您应该检查 DbContextOptionsBuilder.IsConfigured属性:

Gets a value indicating whether any options have been configured.

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);
}

关于c# - 在 DbContext.OnConfiguring 和 AspCore Startup.ConfigureServices 中定义 optionsBuilder 时的预期结果是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49561771/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com