Code First Approach in MVC: Everything You Need to Know

What is Code First Approach?

Code first approach in MVC gets introduced with Entity Framework 4.1. The code first approach is used in the domain-driven design mainly. In this approach, the application domain is considering. The classes are created according to the domain entity instead of the database. After that, the studies have made that match the database design. The diagram below illustrates the code first approach in MVC.

Code First Approach in MVC

As clear from the figure, the entity framework creates or updates the database depending upon the domain classes. Hence, the user needs to code first, and then the entity framework will create the database using the code. That is why it is called the code first approach.

Code First Workflow

The code first approach in MVC follows the workflow with the below steps:

  • Create the domain-driven classes
  • Configure the domain classes created
  • Update or create the database to the domain classes.

The configuration of domain classes occurs using the Fluent API, and the database update is done using the automated migration.

When to Use the Code First Approach in MVC?

  • When the database is to be created.
  • When the application is to be made from scratch.
  • When the operations, such as creation and deletion of views, tables, and stored procedures.
  • When a database has many tables, stored procedures, and ideas.

Before, Introduce code first approach in MVC, used DB First approach commonly. The DB first approach has its advantages and can be preferred over the code first approach in the below cases:

  • When the database is already created in the project.
  • When the project does not involve many updates in the tables or views.
  • When the project is small.

How to Use Code First Approach in MVC?

Before using the code first approach, there are some steps to complete as given below:

1. Create a blank database

  • Open the SQL server and connect with the database server.
  • In object explorer, right-click on the Database option to create a new database.

2. Create MVC Project

  • Navigate to File > New Project > Visual C# > ASP .Net Web Application
  • Enter a name for the solution and project and click Ok.
  • Click on MVC and change the authentication option to Individual User Accounts.

3. Create the Class Library Project

  • Add a new project by right-clicking on the Solution Explorer.
  • Navigate to Visual C# > Windows > Class Library and give the project name as ABC.DAL

4. Add Entity Framework to the DAL project created in the previous step.

  • Navigate to DAL Project > Manage NuGet Packages > abc.DAL.
  • Browse and install the Entity framework.

5. Code First Approach Implementation

Consider the example of an office having many employees working in multiple different departments. If the project involves creating an application for this office, any employee’s information can be viewed and updated. Using the code first approach, the classes will get designed for the office domain first. Consider the two types of Employee and Department, where each employee gets linked to one department.

Create the Employee class as below:

Public Class Employee {

Public int EmpId { get; set; }

Public string EmpName { get; set; }

Public float Age { get; set; }

Public DateTime DateOfJoining { get; set; }

Public float ExpInYears { get; set; }

Public Department Department { get; set; }

}

Create the Department class as below:

Public class Department {

Public int DeptId { get; set; }

Public string DeptName { get; set; }

Public ICollection<Employee> Employee { get; set; }

}

Code first uses the DbContext class to derive the context class. The context class exposes the DBSet, which is the collection of entity classes. The code for the creation of context class is as below:

Namespace EF6Console {

Public class OfficeContext: DbContext {

Public OfficeContext(): base()

{

}

Public DbSet<Employee> Employee { get; set; }

Public DbSet<Department> Department { get; Set; }

}

}

Now as context class is created, add employee using it as below:

Namespace EF6Console {

Class ExProgram {

Static void main(string[], args) {

using(var obj = newOfficeContext())

{

Var emp = new Employee() { EmployeeName = “Peter” };

Obj.Employee.Add(emp);

Obj.SaveChanges();

}

}

}

}

Also Read: Exception Handling Interview Questions

6. Reference DAL Project to UI Project

  • Add reference by right-clicking the References of UI Project.

7. Enable Migration

  • Navigate to Tools > Package Manager > Manage NuGet Packages for Solution and run the below commands:

Enable-Migrations

Add-migration Initial Create

Update-database

8. Add Controller

  • Navigate to Controller > Add > New Controller and select the MVC 5 Controller with views, using Entity Framework.
  • Select the model class, context class, and layout page.

Conclusion

Using the steps shared in this article, you can use the code-first approach in MVC. Using the code first approach, you can create the classes and entities and then update the database.

If you’re interested to learn more about full-stack development, check out upGrad & IIIT-B’s PG Diploma in Full-stack Software Development which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects, and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.

Become a Full Stack Developer

UPGRAD AND IIIT-BANGALORE'S PG DIPLOMA IN SOFTWARE DEVELOPMENT
APPLY NOW

Leave a comment

Your email address will not be published.

×