Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconFull Stack Developmentbreadcumb forward arrow iconCode First Approach in MVC: Everything You Need to Know

Code First Approach in MVC: Everything You Need to Know

Last updated:
25th Feb, 2021
Views
Read Time
6 Mins
share image icon
In this article
Chevron in toc
View All
Code First Approach in MVC: Everything You Need to Know

Navigating through various methodologies to enhance efficiency and clarity in project development, the Code First Approach in MVC stands out as a transformative strategy for software developers. This approach significantly impacts the conception and implementation of database designs within web applications. Traditionally, database schemas were predefined, requiring developers to adapt their code to fit. However, the Code First Approach in MVC reverses this process, allowing developers to define database schemas directly through code, streamlining the development process. This method facilitates a more intuitive development experience and empowers developers to maintain control over the database structure, enabling adjustments as needed without being constrained by a pre-existing database schema.

In this article, I aim to simplify the Code First Approach in MVC, sharing insights on when and how to employ this strategy effectively. Whether you’re a seasoned developer or aspiring to join the field, understanding this approach can refine your project development workflow.

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.

Ads of upGrad blog

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.
Ads of upGrad blog

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

The Code First Approach in MVC represents a paradigm shift in how developers interact with databases in the Model-View-Controller architecture. It empowers developers to focus on the application’s domain model by defining database schemas directly through code rather than traditional database-first methodologies. This approach streamlines the development process, enhances agility, and facilitates a more intuitive alignment between the database layer and application logic. When considering the Code First Approach in MVC, it’s crucial to assess project requirements, team expertise, and the need for flexibility in database design. Implementing this approach effectively requires a solid understanding of entity framework conventions, data annotations, and fluent API configurations. By leveraging the Code First Approach, developers can achieve higher productivity and maintainability in MVC applications, making it an invaluable strategy for modern web development. 

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.

Profile

Pavan Vadapalli

Blog Author
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working on solving problems of scale and long term technology strategy.

Frequently Asked Questions (FAQs)

1What 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.

2What 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.

3How 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.

Explore Free Courses

Suggested Blogs

Top 7 Node js Project Ideas &#038; Topics
31572
Node.JS is a part of the famous MEAN stack used for web development purposes. An open-sourced server environment, Node is written on JavaScript and he
Read More

by Rohan Vats

05 Mar 2024

How to Rename Column Name in SQL
46929
Introduction We are surrounded by Data. We used to store information on paper in enormous file organizers. But eventually, we have come to store it o
Read More

by Rohan Vats

04 Mar 2024

Android Developer Salary in India in 2024 [For Freshers &#038; Experienced]
901323
Wondering what is the range of Android Developer Salary in India? Software engineering is one of the most sought after courses in India. It is a reno
Read More

by Rohan Vats

04 Mar 2024

7 Top Django Projects on Github [For Beginners &amp; Experienced]
52084
One of the best ways to learn a skill is to use it, and what better way to do this than to work on projects? So in this article, we’re sharing t
Read More

by Rohan Vats

04 Mar 2024

Salesforce Developer Salary in India in 2024 [For Freshers &#038; Experienced]
909183
Wondering what is the range of salesforce salary in India? Businesses thrive because of customers. It does not matter whether the operations are B2B
Read More

by Rohan Vats

04 Mar 2024

15 Must-Know Spring MVC Interview Questions
34745
Spring has become one of the most used Java frameworks for the development of web-applications. All the new Java applications are by default using Spr
Read More

by Arjun Mathur

04 Mar 2024

Front End Developer Salary in India in 2023 [For Freshers &#038; Experienced]
902386
Wondering what is the range of front end developer salary in India? Do you know what front end developers do and the salary they earn? Do you know wh
Read More

by Rohan Vats

04 Mar 2024

Method Overloading in Java [With Examples]
26221
Java is a versatile language that follows the concepts of Object-Oriented Programming. Many features of object-oriented programming make the code modu
Read More

by Rohan Vats

27 Feb 2024

50 Most Asked Javascript Interview Questions &#038; Answers [2024]
4383
Javascript Interview Question and Answers In this article, we have compiled the most frequently asked JavaScript Interview Questions. These questions
Read More

by Kechit Goyal

26 Feb 2024

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon