transactionscope mysql,TransactionScope与EntityFramework 6和MySql

I have the following requirement for a project: preform transactions over multiple databases in MySql with EntityFramework (all databases are on the same mysql server).

When trying to solve the issue with TransactionScope, there seems to be an issue with different MySql connection strings:

"Multiple simultaneous connections or connections with different connection strings inside the same transaction are not currently supported."

As a workaround I tried ommiting the database parameter from the connection string, which works if I open the connection and set the database before the .SaveChanges() method is called (by overloading the method in a class that inherits from DbContext). But calling the same statement for each select statement is just not feasable.

My custom class looks like this:

public class ContextBase : DbContext

{

public ContextBase(string connectionStringWithoutDatabase)

: base(connectionStringWithoutDatabase)

{}

public override int SaveChanges()

{

Database.Connection.Open();

Database.Connection.ChangeDatabase("MyDatabaseName");

base.SaveChanges();

Database.Connection.Close();

}

// How to handle Selects?

}

My Unit of work class:

public class UnitOfWork

{

private IEnumerable ContextList

{

get { return _contextList; }

}

private readonly IEnumerable _contextList;

public UnitOfWork(IEnumerable contextList)

{

_contextList = contextList;

}

public void Save()

{

var transactionScope = new TransactionScope();

foreach (DbContext context in ContextList)

{

context.SaveChanges();

}

transactionScope.Complete();

transactionScope.Dispose();

}

}

Another possible workaround would be to create a wrapper in which there would be two DbContext instances - one with the database set for select statements, the other without for the non-query operations. But this just feels wrong.

Now my question(s):

Is there an easier way to do such transactions?

Is it possible to set the database name before an select statement occurs? Is opening the connection in the constructor feasable?

Would the wrapper with two DbContexts be too much overhead?

解决方案

We ended up finding a solution to the problem of setting the database name before each select. To achieve this one must create a class that implements IDbCommandInterceptor and register it with your context. In the different functions of that interface you can change the Database before the SQL is sent to the server.

A rough test also showed no noticable performance degradation.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值