[英]when to provide DbContextOptions in DbContext constructor vs OnConfiguring?
What is the difference between providing a DbContext
constructor that accepts DbContextOptions<MyFileContext>
versus including OnConfiguring
method that wires-up database?提供接受DbContextOptions<MyFileContext>
的DbContext
构造函数与包括连接数据库的OnConfiguring
方法有什么区别?
Are the two are equivalent?两者是等价的吗?
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?两者是等价的吗?
It's complicated.情况很复杂。 (But ideally no); (但理想情况下没有);
The
DbContextOptions
can be supplied to theDbContext
by overriding theOnConfiguring
method or externally via a constructor argument.可以通过重写DbContextOptions
方法或通过构造函数参数在外部将OnConfiguring
提供给DbContext
。If both are used,
OnConfiguring
is applied last and can overwrite options supplied to the constructor argument.如果两者都使用,OnConfiguring
最后应用,并且可以覆盖提供给构造函数参数的选项。
emphasis mine强调我的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.