diff --git a/01.Infrastructure/NDF.Data.Entity/MasterSlaves/DbMasterSlaveCommandInterceptor.cs b/01.Infrastructure/NDF.Data.Entity/MasterSlaves/DbMasterSlaveCommandInterceptor.cs
index 2dd26e9..4ac132b 100644
--- a/01.Infrastructure/NDF.Data.Entity/MasterSlaves/DbMasterSlaveCommandInterceptor.cs
+++ b/01.Infrastructure/NDF.Data.Entity/MasterSlaves/DbMasterSlaveCommandInterceptor.cs
@@ -135,13 +135,20 @@ where this.ValidateContextCanApplyTo(context)
///
protected virtual void UpdateToSlaveIfNeed(DbCommand command, DbInterceptionContext interceptionContext)
{
+ // 判断当前会话是否处于分布式事务中
+ bool isDistributedTran = Transaction.Current != null && Transaction.Current.TransactionInformation.Status != TransactionStatus.Committed;
+
var contexts = from context in interceptionContext.DbContexts
where this.ValidateContextCanApplyTo(context)
select context;
foreach (var context in contexts)
{
- string connectionString = this.GetSlaveConnectionString(context);
+ // 判断该 context 是否处于普通数据库事务中
+ bool isDbTran = context.Database.CurrentTransaction != null;
+ // 如果处于分布式事务或普通事务中,则“禁用”读写分离,处于事务中的所有读写操作都指向 Master
+ string connectionString = isDistributedTran || isDbTran ? this.MasterConnectionString : this.GetSlaveConnectionString(context);
+
this.UpdateConnectionStringIfNeed(command, context.Database.Connection, connectionString);
this.StartServersStateScanIfNeed(context);
}
diff --git a/01.Infrastructure/NDF.Data.Entity/MasterSlaves/DbMasterSlaveConnectionInterceptor.cs b/01.Infrastructure/NDF.Data.Entity/MasterSlaves/DbMasterSlaveConnectionInterceptor.cs
index b65fbc1..f89a91a 100644
--- a/01.Infrastructure/NDF.Data.Entity/MasterSlaves/DbMasterSlaveConnectionInterceptor.cs
+++ b/01.Infrastructure/NDF.Data.Entity/MasterSlaves/DbMasterSlaveConnectionInterceptor.cs
@@ -35,6 +35,16 @@ internal DbMasterSlaveConfigContext Config
}
+ ///
+ /// 在开启一个数据库事务动作执行前瞬间触发。
+ ///
+ ///
+ ///
+ public override void BeginningTransaction(DbConnection connection, BeginTransactionInterceptionContext interceptionContext)
+ {
+ UpdateToMasterIfNeed(connection, interceptionContext, this.Config);
+ }
+
///
/// 在打开数据库连接动作执行前瞬间触发。将数据库连接字符串更新至 EF 数据库主从读写分离服务中配置的相关值。
///
@@ -42,8 +52,19 @@ internal DbMasterSlaveConfigContext Config
///
public override void Opening(DbConnection connection, DbConnectionInterceptionContext interceptionContext)
{
- string connectionString = this.Config.UsableMasterConnectionString;
+ UpdateToMasterIfNeed(connection, interceptionContext, this.Config);
+ }
+ internal static void UpdateToMasterIfNeed(DbConnection connection,
+ DbInterceptionContext interceptionContexts, DbMasterSlaveConfigContext config)
+ {
+ //判断是否是该过滤器的数据库
+ if (!interceptionContexts.DbContexts.Any(config.CanApplyTo))
+ {
+ return;
+ }
+ //比较连接字符串
+ string connectionString = config.UsableMasterConnectionString;
if (!DbMasterSlaveCommandInterceptor.ConnectionStringEquals(connection, connectionString))
{
DbMasterSlaveCommandInterceptor.UpdateConnectionString(connection, connectionString);