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.
- public class Employee
- {
- public int EmpId { get; set; }
- public string Name { get; set; }
- public string Address { get; set; }
- public string Email { get; set; }
- public string MobileNo { get; set; }
- }
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.
- public class EmpDataContext : DbContext
- {
- public DbSet<Employee> employees { get; set; }
- }
Step 3
Now, we have to add a Controller. Go to Controllers folder and add a controller.
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.
- public class DemoController : Controller
- {
- EmpDataContext objDataContext = new EmpDataContext();
-
- public ActionResult EmpDetails()
- {
-
- return View(objDataContext.employees.ToList());
- }
- }
After that, add a View for displaying the employee records. Right-click on action method and add a View.
Step 4
Now, before the retrieval of data, we have to set our connection string in web.confifile.
- <connectionStrings>
- <add name="MySqlConnection" connectionString="Data Source=MANNU;database=MyDemoDB;User Id=sa;Password=123;" providerName="System.Data.SqlClient" />
- </connectionStrings>
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.
- public class EmpDataContext : DbContext
- {
-
- public EmpDataContext()
- : base("name=MySqlConnection")
- {
- }
- public DbSet<Employee> employees { get; set; }
- }
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.
- using System.ComponentModel.DataAnnotations; (Import namespace)
- using System.ComponentModel.DataAnnotations.Schema;
-
- [Table("TblEmployee")]
- public class Employee
- {
- [Key]
- public int EmpId { get; set; }
- public string Name { get; set; }
- public string Address { get; set; }
- public string Email { get; set; }
- public string MobileNo { get; set; }
- }
Step 5
Now, we will run the project and then check in SQL.
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.
- public ActionResult create()
- {
-
- return View();
- }
Now, right-click on Create Action Method and add View.
And, after that, we will write HTML code like below.
- @model Example3.Models.Employee
- @using (Html.BeginForm())
- {
- <div class="form-horizontal">
- <h4>Employee</h4>
- <hr />
-
- <div class="form-group">
- @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
-
- </div>
- </div>
-
- <div class="form-group">
- @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })
-
- </div>
- </div>
-
- <div class="form-group">
- @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
-
- </div>
- </div>
-
- <div class="form-group">
- @Html.LabelFor(model => model.MobileNo, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.MobileNo, new { htmlAttributes = new { @class = "form-control" } })
-
- </div>
- </div>
-
- <div class="form-group">
- <div class="col-md-offset-2 col-md-10">
- <input type="submit" value="Create" class="btn btn-default" />
- </div>
- </div>
- </div>
- }
Now, we will write the code for posting the details.
- [HttpPost]
- public ActionResult create(Employee objEmp)
- {
- objDataContext.employees.Add(objEmp);
- objDataContext.SaveChanges();
- return View();
- }
Now, run the project and insert the data.
After that, click on the Create button. Then we will write the code for retrieving the data.
- EmpDataContext objDataContext = new EmpDataContext();
-
- public ActionResult EmpDetails()
- {
-
- return View(objDataContext.employees.ToList());
- }
Here, right click on the Action method “EmpDetails” and press Add View option. And write below html code,
- @model IEnumerable<Example3.Models.Employee>
-
- <p>
- @Html.ActionLink("Create New", "Create")
- </p>
- <table class="table">
- <tr class="btn-primary">
- <th>
- @Html.DisplayNameFor(model => model.EmpId)
- </th>
- <th>
- @Html.DisplayNameFor(model => model.Name)
- </th>
- <th>
- @Html.DisplayNameFor(model => model.Address)
- </th>
- <th>
- @Html.DisplayNameFor(model => model.Email)
- </th>
- <th>
- @Html.DisplayNameFor(model => model.MobileNo)
- </th>
- <th>Action</th>
- </tr>
-
- @foreach (var item in Model) {
- <tr class="btn-info">
- <td>
- @Html.DisplayFor(modelItem => item.EmpId)
- </td>
- <td>
- @Html.DisplayFor(modelItem => item.Name)
- </td>
- <td>
- @Html.DisplayFor(modelItem => item.Address)
- </td>
- <td>
- @Html.DisplayFor(modelItem => item.Email)
- </td>
- <td>
- @Html.DisplayFor(modelItem => item.MobileNo)
- </td>
- <td>
- @Html.ActionLink("Edit", "Edit", new { id=item.EmpId }) |
- @Html.ActionLink("Details", "Details", new { id = item.EmpId }) |
- @Html.ActionLink("Delete", "Delete", new { id = item.EmpId })
- </td>
- </tr>
- }
-
- </table>
Now, we will see the output.
Now we will write code for seeing the details of a particular employee,
- public ActionResult Details(string id)
- {
- int empId = Convert.ToInt32(id);
- var emp = objDataContext.employees.Find(empId);
- return View(emp);
- }
Here, right click on the Action method “Details” and press Add View option. And write the below html code,
- @model Example3.Models.Employee
-
- <div>
- <h4>Employee</h4>
- <hr />
- <dl class="dl-horizontal">
- <dt>
- @Html.DisplayNameFor(model => model.Name)
- </dt>
-
- <dd>
- @Html.DisplayFor(model => model.Name)
- </dd>
-
- <dt>
- @Html.DisplayNameFor(model => model.Address)
- </dt>
-
- <dd>
- @Html.DisplayFor(model => model.Address)
- </dd>
-
- <dt>
- @Html.DisplayNameFor(model => model.Email)
- </dt>
-
- <dd>
- @Html.DisplayFor(model => model.Email)
- </dd>
-
- <dt>
- @Html.DisplayNameFor(model => model.MobileNo)
- </dt>
-
- <dd>
- @Html.DisplayFor(model => model.MobileNo)
- </dd>
-
- </dl>
- </div>
- <p>
- @Html.ActionLink("Edit", "Edit", new { id = Model.EmpId }) |
- @Html.ActionLink("Back to List", "EmpDetails")
- </p>
Output
Now, we will perform edit functionality so for this we will create edit action method.
- public ActionResult Edit(string id)
- {
- int empId = Convert.ToInt32(id);
- var emp = objDataContext.employees.Find(empId);
- return View(emp);
- }
Now, right click on the Action method “Edit” and press Add View option. And write the below html code,
- @model Example3.Models.Employee
-
- @using (Html.BeginForm())
- {
-
- <div class="form-horizontal">
- <h4>Employee</h4>
- <hr />
-
- @Html.HiddenFor(model => model.EmpId)
-
- <div class="form-group">
- @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
-
- </div>
- </div>
-
- <div class="form-group">
- @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })
-
- </div>
- </div>
-
- <div class="form-group">
- @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
-
- </div>
- </div>
-
- <div class="form-group">
- @Html.LabelFor(model => model.MobileNo, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.MobileNo, new { htmlAttributes = new { @class = "form-control" } })
-
- </div>
- </div>
-
- <div class="form-group">
- <div class="col-md-offset-2 col-md-10">
- <input type="submit" value="Save" class="btn btn-default" />
- </div>
- </div>
- </div>
- }
-
- <div>
- @Html.ActionLink("Back to List", "EmpDetails")
- </div>
Now , we will check the output .
Now, we will write the code for updating the page.
- [HttpPost]
- public ActionResult Edit(Employee objEmp)
- {
- var data = objDataContext.employees.Find(objEmp.EmpId);
- if(data != null)
- {
- data.Name = objEmp.Name;
- data.Address = objEmp.Address;
- data.Email = objEmp.Email;
- data.MobileNo = objEmp.MobileNo;
- }
- objDataContext.SaveChanges();
- return View();
- }
After clicking on the Update button the data will be updated.
So, finally we write code for Delete operation.
- public ActionResult Delete(string id)
- {
- int empId = Convert.ToInt32(id);
- var emp = objDataContext.employees.Find(empId);
- return View(emp);
- }
Right click on the Delete Action method and add the view. And we will write the HTML code.
- @model Example3.Models.Employee
-
- <h3>Are you sure you want to delete this?</h3>
- <div>
- <h4>Employee</h4>
- <hr />
- @using (Html.BeginForm())
- {
- @Html.AntiForgeryToken()
- <dl class="dl-horizontal">
- @Html.HiddenFor(model => model.EmpId)
- <dt>
- @Html.DisplayNameFor(model => model.Name)
- </dt>
-
- <dd>
- @Html.DisplayFor(model => model.Name)
- </dd>
-
- <dt>
- @Html.DisplayNameFor(model => model.Address)
- </dt>
-
- <dd>
- @Html.DisplayFor(model => model.Address)
- </dd>
-
- <dt>
- @Html.DisplayNameFor(model => model.Email)
- </dt>
-
- <dd>
- @Html.DisplayFor(model => model.Email)
- </dd>
-
- <dt>
- @Html.DisplayNameFor(model => model.MobileNo)
- </dt>
-
- <dd>
- @Html.DisplayFor(model => model.MobileNo)
- </dd>
-
- </dl>
-
- <div class="form-actions no-color">
- <input type="submit" value="Delete" class="btn btn-default" /> |
- @Html.ActionLink("Back to List", "EmpDetails")
- </div>
- }
- </div>
We will see the Output.
Here, when click the Delete button then the Data will be deleted.
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”.