CRUD Operation With Repository And Database Initialization In Code First Approach In MVC - Part Six

In the previous article, I explained about Code-First Migrations and how to enable those. In this article, I will explain how to perform CRUD and how to perform searching functionality using the code-first approach and Repository. And also in this article, I will give a brief introduction of Database Initialization. Let’s see step by step.

See the previous articles for basic details.

Step 1

Open Visual Studio and go to File >> Project >> Web application and click OK. Then, it will open a window. In that window, select MVC or Empty.

MVC 

Step2

First, we will right-click on the Solution Explorer in our project >> Add >> New item.

MVC

MVC

MVC

Step 3

Now, we will add a domain class so here, I am taking an employee class. Right click on the Models folder and add a class.

  1. [Table("TblEmployee")]  
  2.     public class Employee  
  3.     {  
  4.         [Key]  
  5.         public int EmpId { get; set; }  
  6.         [Required()]  
  7.         [StringLength(100, MinimumLength = 4)]  
  8.         public string Name { get; set; }  
  9.         [Required()]  
  10.         [StringLength(200, MinimumLength = 10)]  
  11.   
  12.         public string Address { get; set; }  
  13.         [Required()]  
  14.         [StringLength(200, MinimumLength = 5)]  
  15.         public string Email { get; set; }  
  16.         [Required()]  
  17.         [StringLength(10, MinimumLength = 10)]  
  18.   
  19.         public string MobileNo { get; set; }  
  20.     }  

Now, we will create a DbContext class inside the Models folder. For that, right click on the Models folder and add a class.

MVC

And write the below code.

  1. public class EmpDataContext : DbContext  
  2.     {        
  3.         public EmpDataContext()  
  4.             : base("name=MySqlConnection")  
  5.         {  
  6.              
  7.         }  
  8.         public DbSet<Employee> employees { get; set; }  
  9.     }  

After that, go in web.config and set the connection string.

  1. <connectionStrings>  
  2.   <add name="MySqlConnection" connectionString="Data Source=MANNU;database=MyDemoDB;User Id=sa;Password=123;"  
  3.        providerName="System.Data.SqlClient" />  
  4. </connectionStrings>  

Step 4

After that, build the project and then it will automatically generate the database or table in SQL so, we can check also in the SQL Server.

MVC

Step 5

Now, we will add a repository class inside the Models folder. Right click on the Models folder and add Repositories folder and add a class inside the Repositories folder.

MVC
  1. public class Repository<T> where T : class  
  2.  {  
  3.      EmpDataContext objDataContext = null;  
  4.      protected DbSet<T> DbSet  
  5.      {  
  6.          get;set;  
  7.      }  
  8.      public Repository()  
  9.      {  
  10.          objDataContext = new EmpDataContext();  
  11.         DbSet = objDataContext.Set<T>();  
  12.      }  
  13.   
  14.      public Repository(EmpDataContext objDataContext)  
  15.      {  
  16.          this.objDataContext = objDataContext;  
  17.      }  
  18.      public List<T> GetAll()  
  19.      {  
  20.          return DbSet.ToList();  
  21.      }  
  22.   
  23.      public T GetById(int id)  
  24.      {  
  25.          return DbSet.Find(id);  
  26.      }  
  27.      public void Add(T entity)  
  28.      {  
  29.          DbSet.Add(entity);  
  30.      }  
  31.      public void Delete(T entity)  
  32.      {  
  33.          DbSet.Remove(entity);  
  34.      }  
  35.      public void SaveChanged()  
  36.      {  
  37.          objDataContext.SaveChanges();  
  38.      }  
  39.  }  

Step 6

Now, we will go in the Controller class and create an object of our repository class.

MVC

Now, we will complete our CRUD operation using the Code First approach with repository class. First, we will write the code for the Create operation. For this, we have to create the action method for getting the request and posting the records named as Create method.

  1. public ActionResult create()  
  2.       {  
  3.   
  4.           return View();  
  5.       }  
  6.       [HttpPost]  
  7.       public ActionResult create(Employee objEmp)  
  8.       {  
  9.           objRepository.Add(objEmp);  
  10.           objRepository.SaveChanged();  
  11.           return View();  
  12.       }  

And, after that, we will write HTML code like below.

  1. @model Example3.Models.Employee  
  2.   
  3.   
  4. @using (Html.BeginForm())   
  5. {  
  6.       
  7.     <div class="form-horizontal">  
  8.         <h4>Employee</h4>  
  9.         <hr />  
  10.         @Html.ValidationSummary(true""new { @class = "text-danger" })  
  11.         <div class="form-group">  
  12.             @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })  
  13.             <div class="col-md-10">  
  14.                 @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })  
  15.                 @Html.ValidationMessageFor(model => model.Name, ""new { @class = "text-danger" })  
  16.             </div>  
  17.         </div>  
  18.   
  19.         <div class="form-group">  
  20.             @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })  
  21.             <div class="col-md-10">  
  22.                 @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })  
  23.                 @Html.ValidationMessageFor(model => model.Address, ""new { @class = "text-danger" })  
  24.             </div>  
  25.         </div>  
  26.   
  27.         <div class="form-group">  
  28.             @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })  
  29.             <div class="col-md-10">  
  30.                 @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })  
  31.                 @Html.ValidationMessageFor(model => model.Email, ""new { @class = "text-danger" })  
  32.             </div>  
  33.         </div>  
  34.   
  35.         <div class="form-group">  
  36.             @Html.LabelFor(model => model.MobileNo, htmlAttributes: new { @class = "control-label col-md-2" })  
  37.             <div class="col-md-10">  
  38.                 @Html.EditorFor(model => model.MobileNo, new { htmlAttributes = new { @class = "form-control" } })  
  39.                 @Html.ValidationMessageFor(model => model.MobileNo, ""new { @class = "text-danger" })  
  40.             </div>  
  41.         </div>  
  42.   
  43.         <div class="form-group">  
  44.             <div class="col-md-offset-2 col-md-10">  
  45.                 <input type="submit" value="Create" class="btn btn-default" />  
  46.             </div>  
  47.         </div>  
  48.     </div>  
  49. }  
  50.   
  51. <div>  
  52.     @Html.ActionLink("Back to List""EmpDetails")  
  53. </div>  

Now, we will write the code for posting the details.

MVC

After that, click on the Create button. Then, it will save the records in the database.

Now, we will write the code for retrieving the data.

  1. public ActionResult EmpDetails()  
  2.      {  
  3.         return View(objRepository.GetAll());                   
  4.           
  5.      }  

Here, right click on the Action method “EmpDetails” and press Add View option. And write the below HTML code.

  1. @model IEnumerable<Example3.Models.Employee>  
  2.   
  3. <p>  
  4.     @Html.ActionLink("Create New""Create")  
  5. </p>  
  6. <table class="table">  
  7.     <tr class="btn-primary">  
  8.         <th>  
  9.             @Html.DisplayNameFor(model => model.EmpId)  
  10.         </th>  
  11.         <th>  
  12.             @Html.DisplayNameFor(model => model.Name)  
  13.         </th>  
  14.         <th>  
  15.             @Html.DisplayNameFor(model => model.Address)  
  16.         </th>  
  17.         <th>  
  18.             @Html.DisplayNameFor(model => model.Email)  
  19.         </th>  
  20.         <th>  
  21.             @Html.DisplayNameFor(model => model.MobileNo)  
  22.         </th>  
  23.         <th>Action</th>  
  24.     </tr>  
  25.   
  26. @foreach (var item in Model) {  
  27.     <tr class="btn-info">  
  28.         <td>  
  29.             @Html.DisplayFor(modelItem => item.EmpId)  
  30.         </td>  
  31.         <td>  
  32.             @Html.DisplayFor(modelItem => item.Name)  
  33.         </td>  
  34.         <td>  
  35.             @Html.DisplayFor(modelItem => item.Address)  
  36.         </td>  
  37.         <td>  
  38.             @Html.DisplayFor(modelItem => item.Email)  
  39.         </td>  
  40.         <td>  
  41.             @Html.DisplayFor(modelItem => item.MobileNo)  
  42.         </td>  
  43.         <td>  
  44.             @Html.ActionLink("Edit""Edit"new {  id=item.EmpId }) |  
  45.             @Html.ActionLink("Details""Details"new { id = item.EmpId }) |  
  46.             @Html.ActionLink("Delete""Delete"new { id = item.EmpId })  
  47.         </td>  
  48.     </tr>  
  49. }  
  50.   
  51. </table>  

Now, we will see the output.

MVC

 

Now, we will write code for seeing the details of a particular employee.

  1. public ActionResult Details(string id)  
  2.       {  
  3.           int empId = Convert.ToInt32(id);  
  4.           var emp = objRepository.GetById(empId);  
  5.           return View(emp);  
  6.       }  

Here, right click on the Action method “Details” and press Add View option. And write the below html code,

  1. @model Example3.Models.Employee  
  2.   
  3. <div>  
  4.     <h4>Employee</h4>  
  5.     <hr />  
  6.     <dl class="dl-horizontal">  
  7.         <dt>  
  8.             @Html.DisplayNameFor(model => model.Name)  
  9.         </dt>  
  10.   
  11.         <dd>  
  12.             @Html.DisplayFor(model => model.Name)  
  13.         </dd>  
  14.   
  15.         <dt>  
  16.             @Html.DisplayNameFor(model => model.Address)  
  17.         </dt>  
  18.   
  19.         <dd>  
  20.             @Html.DisplayFor(model => model.Address)  
  21.         </dd>  
  22.   
  23.         <dt>  
  24.             @Html.DisplayNameFor(model => model.Email)  
  25.         </dt>  
  26.   
  27.         <dd>  
  28.             @Html.DisplayFor(model => model.Email)  
  29.         </dd>  
  30.   
  31.         <dt>  
  32.             @Html.DisplayNameFor(model => model.MobileNo)  
  33.         </dt>  
  34.   
  35.         <dd>  
  36.             @Html.DisplayFor(model => model.MobileNo)  
  37.         </dd>  
  38.   
  39.     </dl>  
  40. </div>  
  41. <p>  
  42.     @Html.ActionLink("Edit""Edit"new { id = Model.EmpId }) |  
  43.     @Html.ActionLink("Back to List""EmpDetails")  
  44. </p>  

MVC

Now, we will perform edit functionality so for this we will create edit action method.

  1. public ActionResult Edit(string id)  
  2.         {  
  3.             int empId = Convert.ToInt32(id);  
  4.             var emp = objRepository.GetById(empId);  
  5.             return View(emp);  
  6.         }  

Now, right click on the Action method “Edit” and press Add View option. And write the below html code,

  1. @model Example3.Models.Employee  
  2.   
  3. @using (Html.BeginForm())  
  4. {  
  5.        
  6.     <div class="form-horizontal">  
  7.         <h4>Employee</h4>  
  8.         <hr />  
  9.   
  10.         @Html.HiddenFor(model => model.EmpId)  
  11.   
  12.         <div class="form-group">  
  13.             @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })  
  14.             <div class="col-md-10">  
  15.                 @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })  
  16.       
  17.             </div>  
  18.         </div>  
  19.   
  20.         <div class="form-group">  
  21.             @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })  
  22.             <div class="col-md-10">  
  23.                 @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })  
  24.              
  25.             </div>  
  26.         </div>  
  27.   
  28.         <div class="form-group">  
  29.             @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })  
  30.             <div class="col-md-10">  
  31.                 @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })  
  32.               
  33.             </div>  
  34.         </div>  
  35.   
  36.         <div class="form-group">  
  37.             @Html.LabelFor(model => model.MobileNo, htmlAttributes: new { @class = "control-label col-md-2" })  
  38.             <div class="col-md-10">  
  39.                 @Html.EditorFor(model => model.MobileNo, new { htmlAttributes = new { @class = "form-control" } })  
  40.                
  41.             </div>  
  42.         </div>  
  43.   
  44.         <div class="form-group">  
  45.             <div class="col-md-offset-2 col-md-10">  
  46.                 <input type="submit" value="Update" class="btn btn-default" />  
  47.             </div>  
  48.         </div>  
  49.     </div>  
  50. }  
  51.   
  52. <div>  
  53.     @Html.ActionLink("Back to List""EmpDetails")  
  54. </div>  

Now, we will write the code for updating the page.

  1. [HttpPost]  
  2.        public ActionResult Edit(Employee objEmp)  
  3.        {  
  4.          var data = objRepository.GetById(objEmp.EmpId);  
  5.            if(data != null)  
  6.            {  
  7.                data.Name = objEmp.Name;  
  8.                data.Address = objEmp.Address;  
  9.                data.Email = objEmp.Email;  
  10.                data.MobileNo = objEmp.MobileNo;                 
  11.            }  
  12.            objRepository.SaveChanged();  
  13.            return View();  
  14.        }  

MVC

MVC

So, finally we write code for Delete operation.
  1. public ActionResult Delete(string id)  
  2.         {  
  3.             int empId = Convert.ToInt32(id);  
  4.             var emp = objRepository.GetById(empId);  
  5.             return View(emp);  
  6.         }  
  7.         [HttpPost]  
  8.         public ActionResult Delete(Employee objEmp)  
  9.         {  
  10.             var emp = objRepository.GetById(objEmp.EmpId);  
  11.             objRepository.Delete(emp);  
  12.             objRepository.SaveChanged();  
  13.             return View("EmpDetails");  
  14.         }  

Right click on the Delete Action method and add the view. And we will write the HTML code.

  1. @model Example3.Models.Employee  
  2.   
  3. <h3>Are you sure you want to delete this?</h3>  
  4. <div>  
  5.     <h4>Employee</h4>  
  6.     <hr />  
  7. @using (Html.BeginForm())  
  8. {  
  9.     @Html.AntiForgeryToken()  
  10.     <dl class="dl-horizontal">  
  11.         @Html.HiddenFor(model => model.EmpId)  
  12.         <dt>  
  13.             @Html.DisplayNameFor(model => model.Name)  
  14.         </dt>  
  15.   
  16.         <dd>  
  17.             @Html.DisplayFor(model => model.Name)  
  18.         </dd>  
  19.   
  20.         <dt>  
  21.             @Html.DisplayNameFor(model => model.Address)  
  22.         </dt>  
  23.   
  24.         <dd>  
  25.             @Html.DisplayFor(model => model.Address)  
  26.         </dd>  
  27.   
  28.         <dt>  
  29.             @Html.DisplayNameFor(model => model.Email)  
  30.         </dt>  
  31.   
  32.         <dd>  
  33.             @Html.DisplayFor(model => model.Email)  
  34.         </dd>  
  35.   
  36.         <dt>  
  37.             @Html.DisplayNameFor(model => model.MobileNo)  
  38.         </dt>  
  39.   
  40.         <dd>  
  41.             @Html.DisplayFor(model => model.MobileNo)  
  42.         </dd>  
  43.     </dl>  
  44.         <div class="form-actions no-color">  
  45.             <input type="submit" value="Delete" class="btn btn-default" /> |  
  46.             @Html.ActionLink("Back to List""EmpDetails")  
  47.         </div>  
  48.     }  
  49. </div>  

MVC

After clicking the  delete button it will be deleted,

MVC

 

Step 7

Now, we will do search functionality. Here, we will search by employee name so first go to employee details, view page and add html code on top,

  1. @using (Html.BeginForm())  
  2. {  
  3. <div class="row">  
  4.     <div class="col-md-2"> Search By Name</div>  
  5.     <div class="col-md-3"><input type="text" name="Name" class="form-control" /></div>  
  6.     <div class="col-md-3"><button type="submit" class="btn btn-info col-md-6 glyphicon-search" value="Search">Search</button></div>  
  7.     
  8.    
  9. </div>  
  10. }  
  11. <br />  
  12. <br />  

MVC

Now, again we will go in model folder and add a class and write the below code,
  1. public class EmployeeRepository : Repository<Employee>  
  2.     {  
  3.         public List<Employee> GetByName(string name)  
  4.         {  
  5.            return DbSet.Where(a => a.Name.Contains(name)).ToList();  
  6.         }  
  7.     }  

Then, we will go in our controller and write the below method

  1. [HttpPost]  
  2.       public ActionResult EmpDetails(string Name)  
  3.       {  
  4.           if (Name == "")  
  5.           {  
  6.               return View(objRepository.GetAll());  
  7.           }  
  8.           else  
  9.           {  
  10.               EmployeeRepository obj = new EmployeeRepository();  
  11.               return View(obj.GetByName(Name));  
  12.           }  
  13.   
  14.   
  15.       }   

And Run the application and enter an employee name in text box and click search button and see the output.

MVC

 

Step 8

Now I explain about Database Initialization in brief.

A database initializer is a class. It takes the responsibility creation of database and initialization in a Code First application. When we will run the application using the code first approach it will automatically create a database but when we will need to modify the data base or alter the database according to our modified domain classes then we will use database initializer. For more details go this link.

Some required points of database initialization

  • Entity Framework provides database initializers to create state
  • Create a class that inherits from appropriate option

    • CreatedatabaseIf Not Exist
    • DropCreateDatabaseIfModelChanges
    • DropCreateDatabaseAlways
    • Custom DB Initializer

  • Override the Seed method to create  database content
  • Register the method with SetInitializer

Now, we will go inside model folder and a class give then name EmpDataContextInitializer,

MVC

Write the below code. 

  1. public class EmpDataContextInitializer : DropCreateDatabaseAlways<EmpDataContext>  
  2.  {  
  3.      protected override void Seed(EmpDataContext context)  
  4.      {  
  5.          
  6.          Employee empObj = new Employee { Name = "Mithilesh", Address = "Hyderabad", Email = "[email protected]", MobileNo = "9823423432" };  
  7.            
  8.          context.employees.Add(empObj);           
  9.   
  10.          context.SaveChanges();  
  11.      }  
  12.  }  

And now, we will go Global.asax and go inside Application_Start().

  1. Database.SetInitializer<EmpDataContext>(new EmpDataContextInitializer());  

 

MVC

See the output.

 

MVC

Also, check in the database,

MVC

Summary

Finally, we knew how to perform CRUD Operation and also searching functionality by employee name using Code First approach and Repository pattern and also we knew about some brief Introduction of database initialization with a practical example. In our next article, we will see “How to give relationships among multiple tables using the Code First approach”.


Similar Articles