Asp.net

Entity Framework Core 同一個 DBContext 上的多個連接字元串?

  • October 20, 2020

我有一個帶有 Entity Framework Core 的 Asp.Net Core 應用程序,我初始化如下:

services.AddDbContext<ApplicationDbContext>(options => 
        options.UseSqlServer(sqlConnectionString));

這很好用,但是我有一個場景,我需要從主數據庫讀取/寫入以進行正常操作,但對於某些操作,我需要從備用伺服器(我們用於報告的只讀複製目標)讀取。

使用新的核心 API 通過依賴注入和 StartUp.cs 中的配置完成所有操作的方式,我如何切換連接字元串,但使用相同的 ApplicationDbContext 類?

我知道一種選擇是使用不同的連接字元串向 DI 系統註冊的 ApplicationDbContext 類的副本,但我想避免維護兩個相同的 DBContext 對象,因為有時我需要從不同的數據庫中讀取伺服器(但具有完全相同的架構)。

提前感謝您的任何指點!

您將需要兩個 DbContext。

public class BloggingContext : DbContext
{
   public DbSet<Blog> Blogs { get; set; }
   public DbSet<Post> Posts { get; set; }
}

public class MyBloggingContext : BloggingContext
{

}

public class MyBackupBloggingContext : BloggingContext
{

}

你可以像這樣註冊它們:

public void ConfigureServices(IServiceCollection services)
{
   services.AddDbContext<MyBloggingContext>(options =>
       options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

   services.AddDbContext<MyBackupBloggingContext>(options =>
       options.UseSqlServer(Configuration.GetConnectionString("BackupConnection")));

}

引用自:https://stackoverflow.com/questions/42616408