本文介绍了在DbContext.OnConfiguring和AspCore Startup.ConfigureServices中都定义了optionsBuilder时,预期的结果是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的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 部分:

如果同时使用了OnConfiguringOnConfiguring,则可以覆盖提供给构造函数参数的选项.

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时,预期的结果是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 23:55