在Asp.net 5中,可以通过配置文件(appsettings.json)和依赖注入实现多数据库结构的处理。
{ "ConnectionStrings": { "DefaultConnection": "Server=(localdb)\MSSQLLocalDB;Database=DefaultDb;Trusted_Connection=True;MultipleActiveResultSets=true", "SecondConnection": "Data Source=MySQLServer;Initial Catalog=SecondDb;Integrated Security=True" } }
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext
services.AddDbContext(options =>
options.UseSqlServer(Configuration.GetConnectionString("SecondConnection")));
}
public class MyController : Controller { private readonly DefaultDbContext _defaultDbContext; private readonly SecondDbContext _secondDbContext;
public MyController(DefaultDbContext defaultDbContext, SecondDbContext secondDbContext)
{
_defaultDbContext = defaultDbContext;
_secondDbContext = secondDbContext;
}
public IActionResult Index()
{
var defaultDbData = _defaultDbContext.DefaultTable.ToList();
var secondDbData = _secondDbContext.SecondTable.ToList();
// ... 其他业务代码
return View();
}
}