Raheel Khan
Raheel Khan

Reputation: 14787

Atomic transactions in Entity Framework 4.1 Code First without stored procedures

Is there a way to implement transactions in code first without having to write stored procedures?

I have some scenarios where multi-table entries need to be created with unique guids before a final table entry can be created. Is this something I can code using EF alone?

Upvotes: 1

Views: 1904

Answers (1)

Jayantha Lal Sirisena
Jayantha Lal Sirisena

Reputation: 21366

DbContext.SaveChanges() method uses a transaction . So it is Atomic and you don't want to use stored procedures. The unitOfWork patter is implemented in EF itself to accomplish this.
But let's say you are using two DbContext instances to d your job , then you need to wrap your work with a transaction scope like this,

using (var scpe=new TransactionScope()){
...
context1.SaveChanges();
....
context.SaveChanges();

scope.Complete();
}

SaveChanges operates within a transaction. SaveChanges will roll back that transaction and throw an exception if any of the dirty ObjectStateEntry objects cannot be persisted.

See the documentation

Upvotes: 2

Related Questions