1 public class DbMasterSlaveCommandInterceptor : DbCommandInterceptor 2 { 3 private string masterConnectionString = "server=192.168.0.99;port=3306;user id=root;password=123456;persistsecurityinfo=True;database=testdb"; 4 private string slaveConnectionString = "server=192.168.0.101;port=3306;user id=root;password=123456;persistsecurityinfo=True;database=testdb"; 5 public override void ReaderExecuting(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext) 6 { 7 this.UpdateConnectionString(interceptionContext, this.slaveConnectionString); 8 } 9 public override void ScalarExecuting(DbCommand command, DbCommandInterceptionContext<object> interceptionContext) 10 { 11 this.UpdateConnectionString(interceptionContext, this.slaveConnectionString); 12 } 13 public override void NonQueryExecuting(DbCommand command, DbCommandInterceptionContext<int> interceptionContext) 14 { 15 this.UpdateConnectionString(interceptionContext, this.masterConnectionString); 16 } 17 private void UpdateConnectionString(DbInterceptionContext interceptionContext, string connectionString) 18 { 19 foreach (var context in interceptionContext.DbContexts) 20 { 21 this.UpdateConnectionString(context.Database.Connection, connectionString); 22 } 23 } 24 private void UpdateConnectionString(DbConnection conn, string connectionString) 25 { 26 ConnectionState state = conn.State; 27 if (state == ConnectionState.Open) 28 conn.Close(); 29 conn.ConnectionString = connectionString; 30 if (state == ConnectionState.Open) 31 conn.Open(); 32 } 33 }
接着,在 Global.asax 的启动代码中将该 类型的实体注入 EF 全局执行上下文中。
1 public class MyHttpApplication : HttpApplication 2 { 3 protected void Application_Start() 4 { 5 DbInterception.Add(new DbMasterSlaveCommandInterceptor()); 6 } 7 }
怎么样,原理是不是很简单?当然,如果想要实现一些丰富的配置和扩展功能,就还需要很多其他的代码了,关于这些本人将会在后续文章中逐步介绍!