Programs

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.

Check out our free courses to get an edge over the competition.

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.

Check out upGrad’s Advanced Certification in Cloud Computing

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.

Explore Our Software Development Free Courses

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.

Check out upGrad’s Full Stack Development Bootcamp (JS/MERN)

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.

Explore our Popular Software Engineering Courses

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.

In-Demand Software Development Skills

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.

Read our Popular Articles related to Software Development

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

upGrad’s Exclusive Software and Tech Webinar for you –

SAAS Business – What is So Different?

 

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.

Learn Software Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

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 Executive PG Program 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.

What is an MVC framework?

MVC stands for Model-View-Controller. It is a design pattern used in software engineering. It allows separation of concerns, which makes code easier to test, change and maintain. The Model represents the data and business logic. Usually, this is done in a separate layer outside the user interface. The View is the part of the application that the user sees and interacts with. This is the layer that we are actually designing when we design a user interface. The Controller decides which controller is the most appropriate to handle each request. When a user interacts with the user interface, it sends a request to the controller. The controller handles the request, then sends the response back to the user interface.

What is the code-first approach in MVC?

In the ASP.NET MVC framework, the code-first approach is a development model where you first write the code that creates the data access layer, then you write the code that creates the controllers and views. In the code-first approach, you create a model, which is a class that represents the data in the application. Then you create a data access layer, which is a set of code that reads and writes data to a data store. Note that a code-first approach does not have to use a database. You could use the code-first model to create any kind of data.

How to become a MVC developer?

If you want to become a MVC developer then you have to know a little bit C# or Java. It's a computer language that is used to write computer programs. It's a good idea to learn a little bit of HTML or HTML5. HTML is the language that is used to write web pages. You should learn a little bit of CSS. CSS is the language that is used to style web pages. The final language that you should know is JavaScript. JavaScript is a programming language that is used to add interactivity to web pages. MVC is an acronym that stands for Model View Controller. The Model is the way that information is stored in the computer. The View is how the information is displayed on the screen. The Controller is the part of the game that handles input and outputs information.

Want to share this article?

Become a Full Stack Developer

Leave a comment

Your email address will not be published. Required fields are marked *

Our Popular Software Engineering Courses

Get Free Consultation

Leave a comment

Your email address will not be published. Required fields are marked *

×
Get Free career counselling from upGrad experts!
Book a session with an industry professional today!
No Thanks
Let's do it
Get Free career counselling from upGrad experts!
Book a Session with an industry professional today!
Let's do it
No Thanks