[英]TransactionScope and Entity Framework
I need to wrap some pieces of code around a TransactionScope
. 我需要在
TransactionScope
周围包装一些代码。 The code inside this using
statement calls a managed C++ library, which will call some unmanaged code. using
语句中的代码称为托管C ++库,它将调用一些非托管代码。 I do also want to update my database, which is using Entity Framework. 我也确实想更新使用实体框架的数据库。
Here comes the problem, when doing SaveChanges
on the DbContext
inside the TransactionScope
I always get some sort of Timeout exception in the database layer. 问题来了,当在
TransactionScope
内的DbContext
上执行SaveChanges
时,我总是在数据库层中遇到某种Timeout异常。 I've googled this, and it seems to be a fairly common problem but I haven't found any applicable answers to my problem. 我已经用谷歌搜索了,这似乎是一个相当普遍的问题,但是我没有找到适合我的问题的答案。 This is a snippet of my code
这是我的代码的一部分
using (var transactionScope = new TransactionScope())
{
try
{
//Do call to the managed C++ Library
using (var dbContext = _dbContextFactory.Create())
{
//doing some CRUD Operations on the DbContext
//Probably some more dbContext related stuff
dbContext.SaveChanges(); //Results with a timeout
}
}
catch (Exception)
{
transactionScope.Dispose();
throw;
}
}
I'm using Entity Framework 6.1.3 so I can access the BeginTransaction
on the database, but I also need wrap the C++ calls inside a TransactionScope
. 我正在使用Entity Framework 6.1.3,因此可以访问数据库上的
BeginTransaction
,但还需要将C ++调用包装在TransactionScope
。
Any suggestions? 有什么建议么?
You will need to pass in TransactionScopeOptions
defining your timeout (How long to keep the transaction open). 您将需要传入
TransactionScopeOptions
定义您的超时(保持事务打开的时间)。 An example for the absolute upper limit of timeouts would be: 超时的绝对上限的示例为:
TransactionOptions to = new TransactionOptions();
to.IsolationLevel = IsolationLevel.ReadCommitted;
to.Timeout = TransactionManager.MaximumTimeout;
using (TransactionScope ts = new TransactionScope(TransactionScopeOption.Required, to)) { }
You should definitely be aware of the impact of such a long-running transaction, this isn't typically required, and I'd highly recommend using something below MaximumTimeout which reflects how long you expect it to run. 您绝对应该意识到这种长时间运行的事务的影响,通常不需要这样做,因此我强烈建议您在MaximumTimeout下面使用某种值,以反映您希望该事务运行多长时间。 You should do your best to keep the time period for which the transaction is held as small as possible, doing any processing that doesn't have to be a single transaction outside the transaction scope.
您应尽最大努力使事务保持的时间段尽可能小,进行不必在事务范围之外的单个事务的任何处理。
It's also worth noting that depending on the underlying database it can enforce it's own limitations on transaction durations if configured to do so. 还值得注意的是,如果配置了基础数据库,它可以根据事务数据库的持续时间实施自己的限制。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.