Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EntityFramework Transaction - Save to multiple tables

Will the below code rollback the changes if there are any exception while saving?

using (SampleEntities context = new SampleEntities())
{
    //Code Omitted

    context.EmpPercAdjustments.AddRange(pp);
    context.SampleJobs.AddRange(sampleJobs);

    context.SaveChanges();
}

Or

Do I need to use transaction?

using (SampleEntities context = new SampleEntities())
{
    //Code Omitted

    using (System.Data.Entity.DbContextTransaction tranc = context.Database.BeginTransaction( ))
    {
        try
        {
            context.EmpPercAdjustments.AddRange(pp);
            context.SampleJobs.AddRange(sampleJobs);
            context.SaveChanges();
            tranc.Commit();
        }
        catch (Exception ee)
        {
            tranc.Rollback();
        }
    }
}

Are there any advantages of using one over the others?

like image 707
ElectricRouge Avatar asked Mar 10 '23 19:03

ElectricRouge


1 Answers

Yes it will rollback correctly.

In this case, you do not need to run an explicit transaction, because there is one already created by Entity Framework.

Creating a transaction by calling context.Database.BeginTransaction() is good, if you want f.e. to get the Id of just inserted record, something like this:

using (SampleEntities context = new SampleEntities())
{
    using (System.Data.Entity.DbContextTransaction trans = context.Database.BeginTransaction( ))
    {
        context.SampleJobs.Add(newJob);
        context.SaveChanges();
        var jobId = newJob.Id;
        //do other things, then commit or rollback
        trans.Commit();
    }
}

In this case, after calling SaveChanges(), the changes made on context objects are applied (so you can read database generated Id of added object in your scope), but they still have to be commited or rolled back, because changes are only dirty written.

Defining an explicit transaction can also be useful, if you have multiple methods that can modify context objects, but you want to have a final say, if changes they made will be all commited or not.

like image 174
Tomas Chabada Avatar answered Mar 19 '23 12:03

Tomas Chabada