我有一些公司和许多用户。 现在我需要为每个公司建立一个数据库。
必须在MVC Core中解决此问题。和控制DI
答案 0 :(得分:0)
您需要创建几个这样的DataBaseContext类
using Microsoft.EntityFrameworkCore;
namespace Data.Models
{
public class FirstDataContext: DbContext
{
public DbSet<User> Users{ get; set; }
public FirstDataContext(DbContextOptions<FirstDataContext> options)
: base(options)
{
}
}
public class SecondDataContext : DbContext
{
public DbSet<User> Users{ get; set; }
public SecondDataContext(DbContextOptions<SecondDataContext> options)
: base(options)
{
}
}
}
然后在appsettings.json上添加几个包含数据库地址的连接字符串
{
"ConnectionStrings": {
"FirstCompany": "Server=(localdb)\\mssqllocaldb;Database=company1;Trusted_Connection=True;"
},
"SecondCompany": "Server=(localdb)\\mssqllocaldb;Database=company2;Trusted_Connection=True;"
},
}
然后转到StartUp.cs
public void ConfigureServices(IServiceCollection services)
{
string FirstCompany= Configuration.GetConnectionString("FirstCompany");
string SecondCompany= Configuration.GetConnectionString("SecondCompany");
services.AddDbContext<FirstDataContext>(options =>
options.UseSqlServer(connection));
services.AddDbContext<SecondDataContext>(options =>
options.UseSqlServer(connection));
services.AddMvc();
}
DI:
public class HomeController: Controller
{
FirstDataContext fdcntxt;
SecondDataContext sdcntxt;
public HomeController (FirstDataContext fdcntxt, SecondDataContext sdcntxt)
{
this.fdcntxt = fdcntxt;
this.sdcntxt = sdcntxt;
}
}
我认为这应该可行。