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

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

Ads of upGrad blog

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?

Ads of upGrad blog

 

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.

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

Java Free Online Course with Certification [2023]
52710
The PYPL Popularity of Programming Language Index maintains that Java is the second most popular programming language in the world, after Python.  Alt
Read More

by Rohan Vats

20 Sep 2023

Salesforce Developer Salary in India in 2023 [For Freshers &#038; Experienced]
900178
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

20 Sep 2023

Literals In Java: Types of Literals in Java [With Examples]
3125
Summary: In this article, you will learn about Literals in Java. Literals in Java Integral Literals Floating-Point Literals Char Literals String Lit
Read More

by Rohan Vats

17 Sep 2023

Web Developer Salary in India in 2023 [For Freshers &#038; Experienced]
899580
Wondering what is the range of Web Developer Salary in India? World Wide Web is fascinating. Even though it has been around for decades, the idea tha
Read More

by Rohan Vats

17 Sep 2023

Top 20 Project Ideas in C++ For Beginners [2023]
169407
Summary: In this article, you will learn the top project ideas in C++. Take a glimpse below Security Systems Car Rental System Dating Applications E
Read More

by Rohan Vats

14 Sep 2023

Top 20 Trending Android Project Ideas &#038; Topics For Beginners [2023]
192201
Summary: In this article, you will learn the top 20 trending android project ideas & topics. Take a glimpse below. Android-based Function Gener
Read More

by Rohan Vats

13 Sep 2023

14 Exciting PHP Project Ideas &#038; Topics For Beginners [2023]
171045
Summary: In this article, you will learn about 14 exciting PHP project ideas. Build a Clothes Recommendation System Customer Relationship Management
Read More

by Rohan Vats

13 Sep 2023

16 Exciting Javascript Project Ideas &#038; Topics For Beginners [2023]
49050
JavaScript bridges the gap between the material and virtual worlds in the ever-converging worlds of technology and reality. JavaScript has become a vi
Read More

by Rohan Vats

12 Sep 2023

9 Exciting DBMS Project Ideas &#038; Topics For Beginners [2023]
228812
Do you want to work on database projects but don’t know where to start? Then you’ve come to the right place. In today’s article, we’ll discuss some of
Read More

by Rohan Vats

12 Sep 2023

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