Transaction In MVC Using Entity Framework

Introduction

This article explains how to use transactions in ASP. Net MVC using the entity framework code first approach to save records in different tables of a database.
 
What’s the agenda?
 
Here I will show a simple form, where I will be storing the user's basic information in one table and multiple educational details in another table where the educational table will store the user table reference id.
 
Here I have used 
  1. ASP.NET MVC 4
  2. MSSQL 2012 as Database.
  3. Entity Framework code first approach.
  4. From nuget I added reference to Entity Framework.

Step 1: Open Visual Studio 2013, click New Project.

Under Installed, Templates, Visual C#, click Web and provide the name and click OK as per the following image.

 
Step 2

After this a window will pop up from Template, select Empty and then select MVC as in the following screenshot:
 
 
Step 3

After this point from Solution Explorer,  click on Solution, Add, then New Project as in the following image:
 
 
Step 4

After this a window will pop up, click Installed, Visual C#, then Class Library as in the following image and click OK:
 
 
Step 5

Now Rename the Class1 name to User under DbEntity and write the following code: 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel.DataAnnotations;  
  4. using System.ComponentModel.DataAnnotations.Schema;  
  5.   
  6. namespace DbEntity  
  7. {  
  8.     [Table("tblUser")]  
  9.     public class User  
  10.     {  
  11.         [Key]  
  12.         public int RefUserID { getset; }  
  13.         public string EmplCode { getset; }  
  14.         public string EmplName { getset; }  
  15.         public string CreatedBy { getset; }  
  16.         public DateTime? CreatedDate { getset; }  
  17.         public bool IsDeleted { getset; }  
  18.         public string DeletedBy { getset; }  
  19.         public DateTime? DeletedDate { getset; }  
  20.   
  21.         public List<UserEducation> objUsrEducation { getset; }  
  22.     }  
  23. }  
Step 6

Now add another class and name it UserEducation User under DbEntity and write the following code:
  1. using System;  
  2. using System.ComponentModel.DataAnnotations;  
  3. using System.ComponentModel.DataAnnotations.Schema;  
  4.   
  5. namespace DbEntity  
  6. {  
  7.     [Table("tblUsrEducationDetail")]  
  8.     public class UserEducation  
  9.     {  
  10.         [Key]  
  11.         public int ID { getset; }  
  12.         public int RefUserID { getset; }  
  13.         public string InstitutionName { getset; }  
  14.         public string InstitutionType { getset; }  
  15.         public string CreatedBy { getset; }  
  16.         public DateTime? CreatedDate { getset; }  
  17.         public bool IsDeleted { getset; }  
  18.         public string DeletedBy { getset; }  
  19.         public DateTime? DeletedDate { getset; }  
  20.     }  
  21. }  
Step 7

Create a dbContext class as follows. Before creating this class install Entity Framework from NuGet Packages.
  1. using System.Data.Entity;  
  2.   
  3. namespace DbEntity.Constent  
  4. {  
  5.     public class MultiFileDbContext : DbContext  
  6.     {  
  7.         public DbSet<User> ObjUserData { getset; }  
  8.         public DbSet<UserEducation> objUserEducation { getset; }  
  9.     }  
  10. }  
Step 8

Changing Web.Config File,
  1. <connectionStrings>  
  2.     <add name="MultiFileDbContext" connectionString="Data Source=PDM-SABYASA-LA\SQLEXPRESS;Initial Catalog=DemoMultiFileUserDb;User ID=sa;Password=Admin@1234;" providerName="System.Data.SqlClient" />  
  3.   </connectionStrings>  
After this the database with name DemoMultiFileUserDb and tables tblUser and tblUsrEducationDetail with columns as per class parameters will be created after doing an Insert/Update/Delete operation.
 
 Step 9

I have created a Controller for storing user details as per the following codes,
  1. public ActionResult Index()  
  2.        {  
  3.            return View();  
  4.        }  
  5.        [ValidateAntiForgeryToken]  
  6.        [HttpPost]  
  7.        public ActionResult Index(User ObjUserData)  
  8.        {  
  9.            using (var context = new MultiFileDbContext())  
  10.            {  
  11.                using (DbContextTransaction dbTran = context.Database.BeginTransaction())  
  12.                {  
  13.                    try  
  14.                    {  
  15.                        User pd = new User()  
  16.                        {  
  17.                            EmplCode = ObjUserData.EmplCode,  
  18.                            EmplName = ObjUserData.EmplName  
  19.                        };  
  20.                        context.ObjUserData.Add(pd);  
  21.                        context.SaveChanges();  
  22.   
  23.                        var id = pd.RefUserID;  
  24.   
  25.                        var usrFile = ObjUserData.objUsrEducation;  
  26.                        if (usrFile != null)  
  27.                        {  
  28.                            foreach (var item in usrFile)  
  29.                            {  
  30.                                item.RefUserID = id;  
  31.                                context.objUserEducation.Add(item);  
  32.                            }  
  33.                        }  
  34.                        context.SaveChanges();  
  35.                        dbTran.Commit();  
  36.                    }  
  37.                    catch (DbEntityValidationException ex)  
  38.                    {  
  39.                        dbTran.Rollback();  
  40.                        throw;  
  41.                    }  
  42.                }  
  43.            }  
  44.            return View();  
  45.        }  
 Step 10

I have created view as per the controller action,
  1. @{  
  2.     ViewBag.Title = "Index";  
  3. }  
  4. <style>  
  5.     body {  
  6.         font-family: arial;  
  7.         font-size: 12px;  
  8.         margin: 20px;  
  9.     }  
  10.   
  11.     table {  
  12.         border-top: 2px solid #708cb7;  
  13.     }  
  14.   
  15.         table td {  
  16.             font-size: 12px;  
  17.             padding: 5px 20px;  
  18.             border: 1px solid #e1eaf9;  
  19.         }  
  20. </style>  
  21.   
  22. @using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))  
  23. {  
  24.     @Html.AntiForgeryToken()  
  25.     <table>  
  26.         <tr>  
  27.             <td>Emp Code:  </td>  
  28.             <td><input id="txtEmpCode" type="text" name="EmplCode" placeholder="Employee Code"></td>  
  29.         </tr>  
  30.         <tr>  
  31.             <td>Emp Name:</td>  
  32.             <td><input id="txtEmpName" type="text" name="EmplName" placeholder="Employee Name"></td>  
  33.         </tr>  
  34.     </table>  
  35.     <br />  
  36.     <table>  
  37.         <tbody id="_qualification">  
  38.         </tbody>  
  39.         <tfoot>  
  40.             <tr>  
  41.                 <td colspan="7">  
  42.                     <input id="btnAddCertificate" type="button" value="+">  
  43.                 </td>  
  44.             </tr>  
  45.         </tfoot>  
  46. </table>  
  47.     <br/>  
  48.     <button type="submit">SUBMIT</button>  
  49. }  
  50.   
  51. <script type="text/javascript">  
  52.   
  53.     $(document).on('click', '#btnAddCertificate', function () {  
  54.         $.get("../content/Repeater/rptData.html", function (data) {  
  55.             $('#_qualification').append(data);  
  56.         });  
  57.   
  58.         var _time = 1000;  
  59.   
  60.         setTimeout(function () {  
  61.             var i = 0;  
  62.             $('._repeatExp').each(function () {  
  63.                 $(this).find('.txtInstName').attr('name', "objUsrEducation[" + (i) + "].InstitutionName");  
  64.                 $(this).find('.ddlEducationType').attr('name', "objUsrEducation[" + (i) + "].InstitutionType");  
  65.                 i++;  
  66.             });  
  67.         }, _time);  
  68.     });  
  69.   
  70. </script>  
 Step 11

I have also added some js and css along with J query to add and remove more records. You can find all in the attached project files. The view will look like this.
 
 
Hope you like it and also you can download the small application from the attachment.