user8739919
user8739919

Reputation:

How to rollback transaction using LINQ-to-SQL in entity framework?

Here's my code:

TransactionScope trans = new TransactionScope();
dbDataContext db = new dbDataContext()
// did some insert
var user = new User();
user.ID = 1;
user.Name = "Nick";

db.Users.Add(user);

db.SubmitChanges();
trans.Complete();

Now how do I rollback transaction if some error occurs while saving changes?

Upvotes: 3

Views: 10535

Answers (1)

chaosifier
chaosifier

Reputation: 2964

There are two ways in which you can use transactions in entity framework. One using TransactionScope and another using database transaction.

For using database transaction, use the following code example:

using (dbDataContext db = new dbDataContext())
using (var dbContextTransaction = db.Database.BeginTransaction()) 
{
    try
    { 
        var user = new User(){ID = 1, Name = "Nick"};
        db.Users.Add(user);
        db.SaveChanges();
        dbContextTransaction.Commit(); 
    } 
    catch (Exception) 
    { 
        dbContextTransaction.Rollback(); 
    }
} 

And here's an example of EF's TransactionScope:

using (TransactionScope tranScope = new TransactionScope())
using (dbDataContext db = new dbDataContext())
{
    try
    {
        var user = new User(){ID = 1, Name = "Nick"};
        db.Users.Add(user);
        db.SaveChanges();
        tranScope.Complete();
    }
    catch(Exception ex){}
}

As you can see, you don't need to call any Roll-Back method in the case of TransactionScope. If you don't call the Complete() method, the transaction does not get committed and gets rolled back automatically before being disposed.

Upvotes: 8

Related Questions