![](/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.