Entity Framework 4 Transaction Scope

为君一笑 提交于 2019-12-11 11:22:58

问题


I am running 2 INSERTS inside a function. The first one is a non-entity framework INSERT (AD0.NET). The second one is an EntityContext.SaveChanges()

Can I not nest both of these inside a Transaction Scope ?


回答1:


Yes you can

using (TransactionScope scope = new TransactionScope())
{

   InsertRecord();

   context.SaveChanges();

   scope.Complete();
}



回答2:


As Eranga says it is perfectly feasible, if somewhat messy.

See this link for peace of mind on TransactionScope

Also consider setting the isolationlevel for the transaction scope e.g.

TransactionOptions options = new TransactionOptions();
options.IsolationLevel = IsolationLevel.Serializable;

using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, options))
{
// Do something here
}

Two different database inserts (two different concurrent connections) will cause transactionscope to escalate to a distributed transaction. Use DTCPIng.exe to test it will work between the machines in questions.

P.S. Different databases have thier own default isolation levels, so it's best practice to specify this in your code, e.g. SQL Server Express uses Serializable by default, SQL Server (Full Version) does not!



来源:https://stackoverflow.com/questions/7525325/entity-framework-4-transaction-scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!