在使用多个 DbContext 的情况下,可以通过以下方式解决“包括来自不同 DbContext 的模型”的问题:
public class DbContext1 : DbContext
{
public DbSet Entities1 { get; set; }
}
public class DbContext2 : DbContext
{
public DbSet Entities2 { get; set; }
}
public class Entity1
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Entity2
{
public int Id { get; set; }
public string Description { get; set; }
}
public void ConfigureServices(IServiceCollection services)
{
// 配置 DbContext1
services.AddDbContext(options =>
{
options.UseSqlServer(Configuration.GetConnectionString("DbContext1Connection"));
});
// 配置 DbContext2
services.AddDbContext(options =>
{
options.UseSqlServer(Configuration.GetConnectionString("DbContext2Connection"));
});
// 其他配置...
}
public class MyController : Controller
{
private readonly DbContext1 _dbContext1;
private readonly DbContext2 _dbContext2;
public MyController(DbContext1 dbContext1, DbContext2 dbContext2)
{
_dbContext1 = dbContext1;
_dbContext2 = dbContext2;
}
public IActionResult Index()
{
var entities1 = _dbContext1.Entities1.ToList();
var entities2 = _dbContext2.Entities2.ToList();
// 其他逻辑...
return View();
}
}
通过以上步骤,你就可以在一个项目中使用多个 DbContext,并在不同的地方进行操作。
下一篇:包括来自不同文件的处理程序。