How to use Transaction in Entity FrameWork in MVC
Transaction support
1.Entity frame work by default wrap insert , update and delete operation in transaction.
2.Transaction call by EF for every new operation (Insert, Update, Delete) and complete the transaction when it finished.
3.EntityFrameWork 6 Introduced db.BeginTransaction & Database.UseTransaction provide
extra new control over transaction.
ex:-
using (System.Data.Entity.DbContextTransaction dbTran = context.Database.BeginTransaction( ))
{
try
{
Employee emp= new Employee() { EmpName = "newemp" };
context.Employees.Add(emp);
context.Database.ExecuteSqlCommand(
@"UPDATE Employee SET EmpName = 'XYZ'" +
" WHERE Id=1"
);
context.Employees.Remove(emp);
//saves all above operations within one transaction
context.SaveChanges();
//commit transaction
dbTran.Commit();
}
catch (Exception ex)
{
//Rollback transaction if exception occurs
dbTran.Rollback();
}
}
Transaction support
1.Entity frame work by default wrap insert , update and delete operation in transaction.
2.Transaction call by EF for every new operation (Insert, Update, Delete) and complete the transaction when it finished.
3.EntityFrameWork 6 Introduced db.BeginTransaction & Database.UseTransaction provide
extra new control over transaction.
ex:-
using (System.Data.Entity.DbContextTransaction dbTran = context.Database.BeginTransaction( ))
{
try
{
Employee emp= new Employee() { EmpName = "newemp" };
context.Employees.Add(emp);
context.Database.ExecuteSqlCommand(
@"UPDATE Employee SET EmpName = 'XYZ'" +
" WHERE Id=1"
);
context.Employees.Remove(emp);
//saves all above operations within one transaction
context.SaveChanges();
//commit transaction
dbTran.Commit();
}
catch (Exception ex)
{
//Rollback transaction if exception occurs
dbTran.Rollback();
}
}