![](/img/trans.png)
[英]No database provider has been configured for this DbContext, even when passing DbContextOptions to constructor
[英]when to provide DbContextOptions in DbContext constructor vs OnConfiguring?
提供接受DbContextOptions<MyFileContext>
的DbContext
构造函数与包括连接数据库的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);
}
}
}
两者是等价的吗?
情况很复杂。 (但理想情况下没有);
可以通过重写
DbContextOptions
方法或通过构造函数参数在外部将OnConfiguring
提供给DbContext
。如果两者都使用,
OnConfiguring
最后应用,并且可以覆盖提供给构造函数参数的选项。
强调我的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.