Introduction
In this blog we will see how to use transactions in entity framework.
Step 1: Create asp.net web application

Webform1.aspx
- <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="EF_Transcation_Support.WebForm1" %>
- <!DOCTYPE html>
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
- <title></title>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- <table>
- <tr>
- <td>
- <asp:Label ID="Label1" runat="server" Text="EF Transaction" Font-Bold="true"></asp:Label>
- </td>
- </tr>
- </table>
- <br />
- <br />
- <table>
- <tr>
- <td colspan="2">
- <asp:Button ID="Button1" runat="server" Text="Insert Data"
- BackColor="Orange" Font-Bold="true" OnClick="Button1_Click" />
- <br />
- <br />
- </td>
- </tr>
- </table>
- </div>
- </form>
- </body>
- </html>
Webform1.aspx.cs
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- namespace EF_Transcation_Support
- {
- public partial class WebForm1 : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- }
- protected void Button1_Click(object sender, EventArgs e)
- {
- using (EmployeeDBEntities empContext = new EmployeeDBEntities())
- {
- using (var transaction = empContext.Database.BeginTransaction())
- {
- try
- {
- Employee employee = new Employee();
- employee.Id = 1;
- employee.FirstName = "James";
- employee.LastName = "Robert";
- employee.DeptId = 1;
- empContext.Employees.Add(employee);
- empContext.SaveChanges();
- Department dept = new Department();
- dept.DeptId = 1;
- dept.Name = "IT";
- empContext.Departments.Add(dept);
- empContext.SaveChanges();
- transaction.Commit();
- }
- catch (Exception ex)
- {
- transaction.Rollback();
- }
- }
- }
- }
- }
- }
Output of the application looks like this

Summary
In this blog we have seen how we can use transactions in entity framework. Happy coding.

Join the conversation! Your thoughts help the community grow.