I have an Asp.Net Core app with Entity Framework Core that I initialize as follows:
我有一个带有Entity Framework Core的Asp.Net Core应用程序,我初始化如下:
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).
这样工作正常,但我有一个场景,我需要从主数据库读取/写入正常操作,但对于某些操作,我需要从备用服务器读取(复制目标是我们用于报告的只读)。
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?
通过新的Core API通过依赖注入和StartUp.cs中的配置完成所有工作的方式,如何切换连接字符串,但使用相同的ApplicationDbContext类?
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).
我知道有一个选项可能是我使用不同的连接字符串向DI系统注册的ApplicationDbContext类的副本,但是我想避免维护两个相同的DBContext对象,因为有时我需要从不同的数据库中读取服务器(但具有完全相同的架构)。
Thanks in advance for any pointers!
提前感谢任何指针!
1 个解决方案
#1
7
You'll need two DbContexts.
你需要两个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")));
}
#1
7
You'll need two DbContexts.
你需要两个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")));
}