提供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 theDbContext
by overriding theOnConfiguring
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/