实体框架核心在同一DBContext上有多个连接字符串吗? [英] Entity Framework Core multiple connection strings on same DBContext?

查看:114
本文介绍了实体框架核心在同一DBContext上有多个连接字符串吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有Entity Framework Core的Asp.Net Core应用程序,其初始化如下:

I have an Asp.Net Core app with Entity Framework Core that I initialize as follows:

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

这可以正常工作,但是我有一种情况,我需要从主数据库读取/写入数据以进行常规操作,但是对于某些操作,我需要从备用服务器中读取(复制目标是只读的,我们仅将其用于报告) ).

This works fine, but I have a scenario where I need to read/write from the primary database for normal operations but for some operations I need to read from an alternate server (a replication target that's read only that we use for reporting).

通过新的Core API通过依赖注入和StartUp.cs中的配置来完成所有操作的方式,如何切换连接字符串,但使用相同的ApplicationDbContext类?

With the way the new Core API does everything via Dependency Injection and configuration in StartUp.cs, how do I switch connection strings, but use the same ApplicationDbContext class?

我知道一个选择是使用不同的连接字符串在DI系统中注册ApplicationDbContext类的副本,但我想避免维护两个相同的DBContext对象,因为有时我需要从中读取不同的数据库服务器(但具有完全相同的架构).

I know that one option would be to have a duplicate of ApplicationDbContext class that I register with the DI system using a different connection string, but I'd like to avoid maintaining two identical DBContext objects just because sometimes I need to read from a different database server (but with the exact same schema).

在此先感谢任何指针!

推荐答案

您将需要两个DbContext.

You'll need two DbContexts.

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

public class MyBloggingContext : BloggingContext
{

}

public class MyBackupBloggingContext : BloggingContext
{

}

您可以像这样注册它们:

And you can register them like this:

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

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

}

这篇关于实体框架核心在同一DBContext上有多个连接字符串吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆