Code First Approach With CRUD Operation In Entity Framework In MVC - Part Four

In previous article, I have explained how to implement code first approach when we have existing database. Now, I will explain that how to implement code first approach when we don’t have existing database. Let‘s see step by step how to implement it.

In the previous article, I have explained how to implement a code first approach when we have an existing database. Now, I will explain how to implement a code first approach when we don’t have an existing database.  Let‘s see step by step how to implement it.

See the previous articles for basic details.

Step 1

Open Visual Studio >> File >> Project >> Web application >> choose MVC >> OK.

After opening the project, first, we have to create a domain class.

Right-click on Models folder and add a class like below. I am adding an Employee class.

  1. public class Employee  
  2.   {  
  3.       public int EmpId { get; set; }  
  4.       public string Name { get; set; }  
  5.       public string Address { get; set; }  
  6.       public string Email { get; set; }  
  7.       public string MobileNo { get; set; }  
  8.   }  

Step 2

Now, I am going to add a DbContext class. For that, right-click the Models folder and add a class and give the name EmpDataContext:DbContext.

  1. public class EmpDataContext : DbContext  
  2.     {  
  3.         public DbSet<Employee> employees { get; set; }  
  4.     }  

Step 3

Now, we have to add a Controller. Go to Controllers folder and add a controller.

MVC

When we add a controller, in this controller an Index Action method is automatically created. We can change it to a user-friendly method name. Now, create the object of your Dbcontext class and write the logic for retrieval of the data.

MVC
  1. public class DemoController : Controller  
  2.     {  
  3.         EmpDataContext objDataContext = new EmpDataContext();  
  4.         // GET: Demo  
  5.         public ActionResult EmpDetails()  
  6.         {  
  7.               
  8.             return View(objDataContext.employees.ToList());  
  9.         }  
  10.     }  

After that, add a View for displaying the employee records. Right-click on action method and add a View.

MVC

Step 4

Now, before the retrieval of data, we have to set our connection string in web.confifile.

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

Now, set the connection string in DbContext class. If we don’t want to give manual connection string, then when running the project, it will automatically create the connection string with the same name as the class name of DbContext class. If we create manually, then we have to pass our Connection String name in base class parameter.

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

As we know, in this Code First approach when we will run the project, at that moment automatically, it will create the DataBase and the Table; table name will be same as our domain Class name; as below my class name is Employee. If we want to change the table name in a user-friendly name as “ TblEmployee”,  then we can use Table class attribute. Also, we can set the Primary key in SQL table from our program by using the Key class attribute in “[ ]” bracteates.

For using this functionality, we have to import the namespace like below.

  1. using System.ComponentModel.DataAnnotations;           (Import namespace)  
  2. using System.ComponentModel.DataAnnotations.Schema;  
  3.   
  4.     [Table("TblEmployee")]  
  5.     public class Employee  
  6.     {  
  7.         [Key]  
  8.         public int EmpId { get; set; }  
  9.         public string Name { get; set; }  
  10.         public string Address { get; set; }  
  11.         public string Email { get; set; }  
  12.         public string MobileNo { get; set; }  
  13.     }  

Step 5

Now, we will run the project and then check in SQL.

MVC

Step 6

Now, we will complete our CRUD operation using the Code First approach. So for that, we will add one Controller.

First, we will write the code for Create operation. For this, we have to create the action method for getting the request named as Create method.

  1. public ActionResult create()  
  2.       {  
  3.   
  4.           return View();  
  5.       }  

Now, right-click on Create Action Method and add View.

MVC

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

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

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

  1. [HttpPost]  
  2.       public ActionResult create(Employee objEmp)  
  3.       {  
  4.           objDataContext.employees.Add(objEmp);  
  5.           objDataContext.SaveChanges();  
  6.           return View();  
  7.       }  

Now, run the project and insert the data.

MVC
MVC

After that, click on the Create button. Then we will write the code for retrieving the data.

  1. EmpDataContext objDataContext = new EmpDataContext();  
  2.         // GET: Demo  
  3.         public ActionResult EmpDetails()  
  4.         {  
  5.               
  6.             return View(objDataContext.employees.ToList());  
  7.         }  

Here, right click on the Action method “EmpDetails” and press Add View option. And write 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 = objDataContext.employees.Find(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>  

Output

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 = objDataContext.employees.Find(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="Save" 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 check the output .

MVC

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

  1. [HttpPost]  
  2.        public ActionResult Edit(Employee objEmp)  
  3.        {  
  4.          var data =  objDataContext.employees.Find(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.            objDataContext.SaveChanges();  
  13.            return View();  
  14.        }  

MVC

After clicking on the Update button the data will be updated.

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 = objDataContext.employees.Find(empId);  
  5.             return View(emp);  
  6.         }  

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.   
  44.     </dl>  
  45.   
  46.         <div class="form-actions no-color">  
  47.             <input type="submit" value="Delete" class="btn btn-default" /> |  
  48.             @Html.ActionLink("Back to List""EmpDetails")  
  49.         </div>  
  50.     }  
  51. </div>  

We will see the Output.

MVC

Here, when click the Delete button then the Data will be deleted.

MVC

So, here no data is available because we had taken one value.

Summary

Finally, we knew how to perform Code First approach, if the DataBase does not exist with CRUD operation example.

In our next article we will see “How to give relationships among multiple tables using Code First approach”.