开发者

Entity Framework 4 Transaction Scope

开发者 https://www.devze.com 2023-04-06 17:33 出处:网络
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()

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 no开发者_如何学编程t nest both of these inside a Transaction Scope ?


Yes you can

using (TransactionScope scope = new TransactionScope())
{

   InsertRecord();

   context.SaveChanges();

   scope.Complete();
}


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!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号