Introduction

In this blog we will see how to use transactions in entity framework.

Step 1: Create asp.net web application

Webform1.aspx

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="EF_Transcation_Support.WebForm1" %>
  2. <!DOCTYPE html>
  3. <html xmlns="http://www.w3.org/1999/xhtml">
  4. <head runat="server">
  5. <title></title>
  6. </head>
  7. <body>
  8. <form id="form1" runat="server">
  9. <div>
  10. <table>
  11. <tr>
  12. <td>
  13. <asp:Label ID="Label1" runat="server" Text="EF Transaction" Font-Bold="true"></asp:Label>
  14. </td>
  15. </tr>
  16. </table>
  17. <br />
  18. <br />
  19. <table>
  20. <tr>
  21. <td colspan="2">
  22. <asp:Button ID="Button1" runat="server" Text="Insert Data"
  23. BackColor="Orange" Font-Bold="true" OnClick="Button1_Click" />
  24. <br />
  25. <br />
  26. </td>
  27. </tr>
  28. </table>
  29. </div>
  30. </form>
  31. </body>
  32. </html>

Webform1.aspx.cs

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.UI;
  6. using System.Web.UI.WebControls;
  7. namespace EF_Transcation_Support
  8. {
  9. public partial class WebForm1 : System.Web.UI.Page
  10. {
  11. protected void Page_Load(object sender, EventArgs e)
  12. {
  13. }
  14. protected void Button1_Click(object sender, EventArgs e)
  15. {
  16. using (EmployeeDBEntities empContext = new EmployeeDBEntities())
  17. {
  18. using (var transaction = empContext.Database.BeginTransaction())
  19. {
  20. try
  21. {
  22. Employee employee = new Employee();
  23. employee.Id = 1;
  24. employee.FirstName = "James";
  25. employee.LastName = "Robert";
  26. employee.DeptId = 1;
  27. empContext.Employees.Add(employee);
  28. empContext.SaveChanges();
  29. Department dept = new Department();
  30. dept.DeptId = 1;
  31. dept.Name = "IT";
  32. empContext.Departments.Add(dept);
  33. empContext.SaveChanges();
  34. transaction.Commit();
  35. }
  36. catch (Exception ex)
  37. {
  38. transaction.Rollback();
  39. }
  40. }
  41. }
  42. }
  43. }
  44. }

Output of the application looks like this

Summary

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