In this blog, we will be talking about how transactions take place in Entity Framework.
DbContext.Database.BeginTransaction() method creates a new transaction for the underlying database and allows us to commit or roll back changes made to the database using multiple SaveChanges method calls.
The following example demonstrates creating a new transaction object using BeginTransaction(), which is, then, used with multiple SaveChanges() calls.
- using(var context = new SchoolContext()) {
- using(DbContextTransaction transaction = context.Database.BeginTransaction()) {
- try {
- var standard = context.Standards.Add(new Standard() {
- StandardName = "1st Grade"
- });
- context.Students.Add(new Student() {
- FirstName = "Rama2",
- StandardId = standard.StandardId
- });
- context.SaveChanges();
- context.Courses.Add(new Course() {
- CourseName = "Computer Science"
- });
- context.SaveChanges();
- transaction.Commit();
- } catch (Exception ex) {
- transaction.Rollback();
- Console.WriteLine("Error occurred.");
- }
- }
- }
In the above example, we created new entities - Standard, Student, and Course and saved these to the database by calling two SaveChanges(), which execute INSERT commands within one transaction.
If an exception occurs, then the whole changes made to the database will be rolled back.
I hope it's helpful.