EFCore ORM CodeFirst读写分离
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); }