在ASP.NET Core 3.1中,可以使用多个或备选数据库上下文来处理多个数据库连接。下面是一个示例解决方法:
public void ConfigureServices(IServiceCollection services)
{
// 配置AppDbContext
services.AddDbContext(options =>
options.UseSqlServer(Configuration.GetConnectionString("AppDbConnection")));
// 配置LogDbContext
services.AddDbContext(options =>
options.UseSqlServer(Configuration.GetConnectionString("LogDbConnection")));
services.AddControllers();
}
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions options) : base(options)
{
}
// 添加AppDbContext的DbSet和其他配置...
}
public class LogDbContext : DbContext
{
public LogDbContext(DbContextOptions options) : base(options)
{
}
// 添加LogDbContext的DbSet和其他配置...
}
public class HomeController : Controller
{
private readonly AppDbContext _appDbContext;
private readonly LogDbContext _logDbContext;
public HomeController(AppDbContext appDbContext, LogDbContext logDbContext)
{
_appDbContext = appDbContext;
_logDbContext = logDbContext;
}
// 使用_appDbContext和_logDbContext进行数据库操作...
}
{
"ConnectionStrings": {
"AppDbConnection": "Data Source=appdbserver;Initial Catalog=AppDb;Integrated Security=True;",
"LogDbConnection": "Data Source=logdbserver;Initial Catalog=LogDb;Integrated Security=True;"
}
}
这样,你就可以在ASP.NET Core 3.1中使用多个或备选的数据库上下文。在需要使用不同的数据库连接时,只需通过依赖注入获取相应的数据库上下文实例即可。