When we need to perform mutiple operations on an object in database or on multiple objects, then using transaction is considered a good practice as it maintains data consistency
Here is the sample code of how we can use transaction in EF
using (ApplicationDbContext applicationDbContext = new ApplicationDbContext())
{
using (var transaction = applicationDbContext.Database.BeginTransaction())
{
try
{
var twingleInvitees = applicationDbContext.TwingleInvitees.ToList();
foreach (var twingleInvitee in twingleInvitees)
{
twingleInvitee.ResponseCode = (int)response;
}
applicationDbContext.SaveChanges();
transaction.Commit();
}
catch (Exception)
{
transaction.Rollback();
throw;
}
}
}
}
In above code, I am trying to update each entry in the table using foreach loop. There is always a possibility of error in foreach loop so to avoid data inconsistency, i have used transaction here.
Another thing to be noticed is that we are making changes to the items in foreach loop but we are saving the changes outside of loop. This is for code efficiency so that we don`t have to hit database every time we make changes. Though the result of saving inside the loop and outside the loop will be same but our approach of saving it outside the loop will save time and resource
0 Comment(s)