Full Trust European Hosting

BLOG about Full Trust Hosting and Its Technology - Dedicated to European Windows Hosting Customer

European Visual Studio 2017 Hosting - HostForLIFE.eu :: Exporting Comments In Visual Studio

clock October 15, 2020 10:08 by author Peter

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(); //save the changes 
    } catch (Exception ex) { 
        transaction.Rollback(); //rollback the changes on exception 
        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.



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in