C# 何时在DbContext构造函数与OnConfigurang中提供DbContextOptions?
提供接受C# 何时在DbContext构造函数与OnConfigurang中提供DbContextOptions?,c#,asp.net-core,entity-framework-core,C#,Asp.net Core,Entity Framework Core,提供接受DbContext选项的DbContext构造函数与包含连接数据库的onconfigurang方法有什么区别 这两者是等价的吗 using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.SqlServe
DbContext选项的DbContext
构造函数与包含连接数据库的onconfigurang
方法有什么区别
这两者是等价的吗
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.SqlServer;
namespace MyApp.Models
{
public class MyDbContext : DbContext
{
// OPTION 1
public MyDbContext(DbContextOptions<MyFileContext> options) : base(options)
{
}
public DbSet<MyTable> MyTables { get; set; }
// OPTION 2
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
optionsBuilder.UseSqlServer(AppSettingsProvider.MySqlServerConnection);
}
}
}
使用系统;
使用System.Collections.Generic;
使用System.ComponentModel.DataAnnotations.Schema;
使用Microsoft.EntityFrameworkCore;
使用Microsoft.EntityFrameworkCore.SqlServer;
名称空间MyApp.Models
{
公共类MyDbContext:DbContext
{
//选择1
公共MyDbContext(DbContextOptions):基本(选项)
{
}
公共DbSet MyTables{get;set;}
//选择2
配置时受保护的覆盖无效(DBContextOptions Builder Options Builder)
{
基本配置(选项生成器);
optionsBuilder.UseSqlServer(appsetingsProvider.MySqlServerConnection);
}
}
}
这两者是等价的吗
这很复杂。(但理想情况下不是)
DbContextOptions
可以提供给DbContext
,方法是通过构造函数参数在外部重写onconfigurang
方法
如果两者都使用,onconfigurang
将最后应用,并且可以覆盖提供给构造函数参数的选项。
重点矿山
此处解释的参考引自docs re option 2应用程序可以简单地实例化这样的上下文,而无需向其构造函数传递任何内容