I used to rarely use transactions until all of the sudden I was faced with a scenario that had a lot of db footprints, so I panicked and since then started to think about using transactions for any logic that might involve data manipulation statements (Insert, Update, Delete) and could result in unexpected disasters, exceptions.
Here is the model that I keep on using:
using (var db = new X_Entity())
{
using (var trans = db.Database.BeginTransaction())
{
try
{
#region Logic
// Logic that might include at least one data manipulation statement
// db.Insert(), db.Update, db.Delete
#endregion
db.SaveChanges();
trans.Commit();
}
catch (Exception exc)
{
trans.Rollback();
HandleExceptions(exc);
}
}
}
Say there is a single Update, insert or delete statement, should a transaction be used in this case? My understanding is that in the following cases transactions are not necessary to use:
- Get/Select/Join statements...etc
- When the data manipulation statement is not followed by error prone logic