1.首先要有對應的context實體類,
多個實體類的構造函數的參數都應該是集合
public class firstContext : DbContext
{
//多個數據庫應該使用這個構造函數,參數是上下文的集合
public GalpOnlineContext(DbContextOptions<firstContext> options) : base(options)
{
}
//自定義DbContext實體屬性名與數據庫表對應名稱(默認 表名與屬性名對應是 User與Users)
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().ToTable("user");
modelBuilder.Entity<Project>().ToTable("project");
//相關表名稱的和類的對應
base.OnModelCreating(modelBuilder);
}
public DbSet<User> User { get; set; }
//....
//第二種方法,重載父級的構造函數,和配置,這個只能是一個數據庫時候的構造函數
/*
public firstContext(DbContextOptions options) : base(options)
{
// Using the default constructor
}*/
}
}
2.在appsettings.json中進行配置數據庫連接的信息
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"ConnectionStrings": {
"firstContext": "Server=localhost;database=test;uid=root;pwd=123456;sslmode=none",
"secondContext": "Server=localhost;database=test2;uid=root;pwd=123456;sslmode=none"
},
3.在startup.cs文件中注冊數據庫上下文的信息
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// options.CheckConsentNeeded = context => false;實現session,默認是true
options.CheckConsentNeeded = context => false;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
//注冊數據庫的服務
string connectionString = Configuration.GetConnectionString("firstContext");
string connectionString2 = Configuration.GetConnectionString("secondContext");
services.AddDbContext<firstContext>(options => options.UseMySql(connectionString));
services.AddDbContext<secondContext>(options => options.UseMySql(connectionString2));
//注冊session
services.AddDistributedMemoryCache();
services.AddSession(Options =>
{
Options.IdleTimeout = TimeSpan.FromSeconds(1000);
Options.Cookie.HttpOnly = true;
});
//services.AddMemoryCache();//使用本地緩存必須添加
//注冊mvc服務
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
然后就可以了,在使用的地方引入上下文就可以了
public class TestController : Controller { public readonly firstContext _context; //構造函數,依賴注入數據庫上下文就可以了 public TestController(firstContext context) { _context = context; } public ActionResult Index(string page) { List<Project> projects = _context.Project.ToList(); ViewBag.projects = projects; return View(); } }
