Reputation: 8628
I'm having a bito f a problem with EF and transaction processing.
I'm trying to do this:
using(TransactionScope scope = new TransactionScope())
{
using(MyEntities model = new MyEntities())
{
MyT thing = new MyT{ Value1 = "bla", Value2 = "bla2", Value3 = "foo" };
model.MyT.AddObject(thing);
model.SaveChanges();
thing.Value4 = Service.Call("bar");
// this call causes an exception in MSDTC
model.SaveChanges();
scope.Complete();
}
}
The reason i do this is because I want to do an insert in to the db so MyT has a unique id that i passto the service when i make the call i then get back a unique ref and status from the service depicting what happened during the call which i then need to append to the record.
My understanding is that during a single transaction you can only update a record once / make an insert call but you can't do both as this creates a problem for some reason ... i used to have an MSDN article that explained some logical reason why this couldn't be done (likely lock related).
So my problem is how to get round this but ensure that in event of any failure in any of these calls i can still rollback.
Upvotes: 1
Views: 418
Reputation: 65481
Try creating the transactionscope with transaction options. In the transaction options specify ReadUncommitted.
http://msdn.microsoft.com/en-us/library/system.transactions.isolationlevel.aspx
http://msdn.microsoft.com/en-us/library/ms149853.aspx
Upvotes: 0
Reputation: 84
When you make several connections to the db inside the transaction scope, the transaction will be promoted from local transaction to distributed transaction, unless you explicitily use the same connection to the db.
When the transaction is promoted it needs the MSDTC service to manage the transaction, so if this service is not available it will throw an exception.
Something like this:
using(TransactionScope scope = new TransactionScope())
{
using(MyEntities model = new MyEntities())
{
model.Connection.Open();
MyT thing = new MyT{ Value1 = "bla", Value2 = "bla2", Value3 = "foo" };
model.MyT.AddObject(thing);
model.SaveChanges();
thing.Value4 = Service.Call("bar");
// this call shouldn't cause anymore an exception in MSDTC
model.SaveChanges();
scope.Complete();
}
}
Upvotes: 1