EntityFramework ChangeTracker along with MySql Transaction

I was just getting into Entity Framework and I was going through the documentation to get a basic understanding.

All MS examples to save data to a database use the ChangeTracker context in a similar way to how transactions are used in regular SQL (execute all the queries you want and then apply them all at once by calling context.SaveChanges()

) ..

Example from here :

using (var db = new BloggingContext())
{
    var blog = new Blog { Url = "http://sample.com" };
    db.Blogs.Add(blog);
    db.SaveChanges();
}

      

This is good and good. However, looking at the documentation for the MySql Connector , in the EF6 support examples, they use both ChangeTracker and regular transactions.

Example from here :

MySqlTransaction transaction = connection.BeginTransaction();
try
{
    using (Parking context = new Parking(connection, false))
    {
        context.Database.UseTransaction(transaction);

        List<Car> cars = new List<Car>();
        cars.Add(new Car { Manufacturer = "Nissan", Model = "370Z", Year = 2012 });    
        cars.Add(new Car { Manufacturer = "Ford", Model = "Mustang", Year = 2013 });
        cars.Add(new Car { Manufacturer = "Chevrolet", Model = "Camaro", Year = 2012 });
        cars.Add(new Car { Manufacturer = "Dodge", Model = "Charger", Year = 2013 });

        context.Cars.AddRange(cars);
        context.SaveChanges();
    }

    transaction.Commit();
}
catch
{
    transaction.Rollback();
    throw;
}

      

My question is, why use both? Are there any benefits of using transactions in this scenario? If so, are they specific to MySql, or is this true for all vendors?

And to be clear, I understand that using a transaction allows you to undo all changes that were made in the event of an exception, but doesn't get rid of the context without doing the same?

+3


source to share





All Articles