EFCore ORM CodeFirst讀寫分離
阿新 • • 發佈:2021-08-07
public class EFCoreDbContext:DbContext { private string strConn = "Server=.;Database=EFCoreDB01;Trusted_Connection=True"; public EFCoreDbContext(string strConn) { this.strConn = strConn; //strConns.ad } /// <summary>/// 每一個表對應資料庫對映 /// </summary> public DbSet<UserInfo> UserInfo { get; set; } /// <summary> /// 配置資料庫連線 /// </summary> /// <param name="optionsBuilder"></param> protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) {//Nuget引入:Microsoft.EntityFrameworkCore.SqlServer optionsBuilder.UseSqlServer(strConn);//資料庫連線 } /// <summary> /// 配置資料庫結構,關係對映 /// </summary> /// <param name="modelBuilder"></param> protected override void OnModelCreating(ModelBuilder modelBuilder) {//初始化資料庫 modelBuilder.Entity<UserInfo>().HasData(new List<UserInfo>() { new UserInfo() { UserId=1, UserName="張三", Description="好學生", UserAge=33 }, new UserInfo() { UserId=2, UserName="李三", Description="不太好學生", UserAge=31 }, new UserInfo() { UserId=3, UserName="王五", Description="學生", UserAge=34 } }); } }
生成資料庫
1,通過Api生成(下面方法)
2,工具生成
3,遷移檔案生成
EFCoreDbContext context = new EFCoreDbContext(); context.Database.EnsureDeleted();//判斷如果有資料庫,就刪除資料庫 context.Database.EnsureCreated();//建立一個新的資料庫
單Context多資料庫連線管理
public class EFCoreContextFactory { private const string writeConnection = "Server=.;Database=EFCoreDB01;Trusted_Connection=True"; public static List<string> strConns = new List<string>() { "Server=.;Database=EFCoreDB01_Read01;Trusted_Connection=True", "Server=.;Database=EFCoreDB01_Read02;Trusted_Connection=True" }; private static EFCoreDbContext context=null; public static EFCoreDbContext createDbContext(WriteOrRead writeOrRead) { switch (writeOrRead) { case WriteOrRead.Write: context = new EFCoreDbContext(writeConnection); break; //主庫連線 case WriteOrRead.Read: context= new EFCoreDbContext(GetReadConnect()); //從庫連線 break; default: break; } return context; } //1,當前請求數量 private static int _currentRequestCount = 0; private static string GetReadConnect() { //定義一個輪詢策略 //根據請求量來取模 int currentIndex = _currentRequestCount % strConns.Count; _currentRequestCount++; return strConns[currentIndex]; //定義一個隨機策略 // int i = new Random().Next(0, strConns.Count); // return strConns[i]; } } public enum WriteOrRead { Write, Read }
測試程式碼
{ EFCoreDbContext context = EFCoreContextFactory.createDbContext(WriteOrRead.Read); UserInfo user = context.UserInfo.Find(2); } { EFCoreDbContext context = EFCoreContextFactory.createDbContext(WriteOrRead.Read); UserInfo user = context.UserInfo.Find(2); } { EFCoreDbContext context = EFCoreContextFactory.createDbContext(WriteOrRead.Read); UserInfo user = context.UserInfo.Find(2); } { EFCoreDbContext context = EFCoreContextFactory.createDbContext(WriteOrRead.Read); UserInfo user = context.UserInfo.Find(2); }