c# - 何时在 DbContext 构造函数中提供 DbContextOptions 与 OnConfiguring?

标签 c# asp.net-core entity-framework-core

提供DbContext有什么区别?接受 DbContextOptions<MyFileContext> 的构造函数与包含 OnConfiguring连接数据库的方法?

两者等价吗?

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

    }
}

最佳答案

Are the two are equivalent ?

这很复杂。 (但理想情况下不是);

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.

强调我的

引用Configuring a DbContext

关于c# - 何时在 DbContext 构造函数中提供 DbContextOptions 与 OnConfiguring?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58808662/

相关文章:

javascript - 在 JavaScript 中转义的北欧字符

c# - 如何在不等待的情况下等待另一个服务在后台完成任务?

c# - 使用 Entity Framework Core 在运行时迁移

c# - 如何在 EF Core 中添加自定义添加迁移行为?

c# - 文件解析器在 MVVM 设计模式中属于什么位置?

c# - 如何在单元测试中验证序列化的 JSON 在 Python/C# 中是否正确?

c# - HtmlAgilityPack 的替代品?

c# - Linq 相当于 SQL LIKE [a-f]

c# - 身份验证中间件

c# - 将 IEntityTypeConfiguration 与基本实体一起使用