Entity Framework Core 实现读写分离
在之前的版本中我们可用构造函数实现,其实现在的版本也一样,之前来构造连接字符串,现在相似,构造DbContextOptions<T>
代码如下:
public SContext(MasterSlave masterSlave) : base(GetOptions(masterSlave)) { // TODO: #639 //ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; } /// <summary> /// 主从关系 /// </summary> /// <param name="writeRead"></param> /// <returns></returns> private static DbContextOptions<SContext> GetOptions(MasterSlave masterSlave) { var optionsBuilder = new DbContextOptionsBuilder<SContext>(); if (masterSlave == MasterSlave.Slave) { optionsBuilder.UseSqlServer(Config.DbConfig.Read); } else { optionsBuilder.UseSqlServer(Config.DbConfig.Write); } return optionsBuilder.Options; }