Entity Framework in ASP.NET MVC

Introduction

When building web applications in C#, developers often need to connect applications with databases to store and retrieve data.

Traditionally, developers used ADO.NET, where they had to write many SQL queries manually. This process can become complex and time-consuming.

To make database operations easier, Microsoft introduced Entity Framework (EF).

Entity Framework allows developers to work with databases using C# objects instead of writing SQL queries manually.

In this beginner-friendly guide, we will learn:

  • What Entity Framework is

  • Why developers use it

  • Different approaches of Entity Framework

  • How to create a simple CRUD application using Entity Framework in ASP.NET MVC

Everything is explained in easy words and simple steps.

What is Entity Framework?

Entity Framework is an Object Relational Mapper (ORM) developed by Microsoft.

It allows developers to interact with a database using C# classes instead of writing SQL queries.

Simple Idea

Database Table → C# Class
Table Rows → Objects

This makes coding simpler, cleaner, and faster.

Why Use Entity Framework?

Entity Framework provides several advantages.

1 Less Code

You don't need to write many SQL queries.

2 Faster Development

Database operations become quicker to implement.

3 Strongly Typed Data

You work with C# objects instead of raw database data.

4 Automatic Mapping

Entity Framework automatically maps database tables to C# classes.

Types of Entity Framework Approaches

Entity Framework supports three main approaches.

1 Database First

In this approach:

  • Database is created first

  • Entity Framework generates classes from database tables

2 Code First

In this approach:

  • Classes are created first

  • Database tables are automatically generated from classes

3 Model First

Database structure is designed visually using a model.

For beginners, Code First is the easiest approach, so we will use it in this tutorial.

Step 1: Create ASP.NET MVC Project

Open Visual Studio

  1. Click Create New Project

  2. Select ASP.NET Web Application (.NET Framework)

  3. Choose MVC Template

Your MVC project is now ready.

Step 2: Install Entity Framework

Open NuGet Package Manager Console and run:

Install-Package EntityFramework

This installs the Entity Framework library in your project.

Step 3: Create Model Class

Create a folder called Models and add a class.

Student.cs

public class Student
{
    public int Id { get; set; }

    public string Name { get; set; }

    public string Email { get; set; }

    public string Course { get; set; }
}

Explanation

This class represents a Student table in the database.

Each property will become a column in the database.

Step 4: Create Database Context

Now create a DbContext class.

StudentContext.cs

using System.Data.Entity;

public class StudentContext : DbContext
{
    public DbSet<Student> Students { get; set; }
}

Explanation

DbContext represents a session with the database.

DbSet<Student> represents the Student table.

Step 5: Add Connection String

Open Web.config and add:

<connectionStrings>
  <add name="StudentContext"
       connectionString="Data Source=.;Initial Catalog=StudentDB;Integrated Security=True"
       providerName="System.Data.SqlClient"/>
</connectionStrings>

This tells the application how to connect to SQL Server.

Step 6: Create Controller

Now create a StudentController.

public class StudentController : Controller
{
    StudentContext db = new StudentContext();

    public ActionResult Index()
    {
        var students = db.Students.ToList();
        return View(students);
    }
}

Explanation

Here we are retrieving all students from the database using Entity Framework.

Step 7: Create Student (Insert Data)

public ActionResult Create()
{
    return View();
}

[HttpPost]
public ActionResult Create(Student student)
{
    db.Students.Add(student);
    db.SaveChanges();

    return RedirectToAction("Index");
}

Explanation

Add() → adds data to database

SaveChanges() → saves changes to database

Step 8: Read Data

public ActionResult Index()
{
    var students = db.Students.ToList();
    return View(students);
}

Explanation

ToList() retrieves all records from the database.

Step 9: Update Data

public ActionResult Edit(int id)
{
    var student = db.Students.Find(id);
    return View(student);
}

[HttpPost]
public ActionResult Edit(Student student)
{
    db.Entry(student).State = EntityState.Modified;
    db.SaveChanges();

    return RedirectToAction("Index");
}

Explanation

  • Find(id) retrieves specific record

  • EntityState.Modified updates the record

Step 10: Delete Data

public ActionResult Delete(int id)
{
    var student = db.Students.Find(id);

    db.Students.Remove(student);
    db.SaveChanges();

    return RedirectToAction("Index");
}

Explanation

Remove() deletes the record from database.

Output

After running the application, users can:

✔ Add Student

✔ View Student List

✔ Edit Student

✔ Delete Student

All database operations are handled using Entity Framework.

Advantages of Entity Framework

Entity Framework simplifies database development.

Key benefits include:

  • Faster development

  • Less SQL code

  • Object-oriented database access

  • Automatic mapping

Because of these benefits, Entity Framework is widely used in modern .NET applications.

Common Mistakes Beginners Make

Beginners often:

  • Forget to call SaveChanges()

  • Confuse DbSet with database tables

  • Do not configure connection strings correctly

Understanding these basics helps avoid common issues.

Conclusion

Entity Framework makes working with databases much easier for developers.

Instead of writing complex SQL queries, developers can work with C# classes and objects, making code more readable and maintainable.

In this tutorial, we learned how to:

  • Understand Entity Framework basics

  • Create models and DbContext

  • Perform CRUD operations in ASP.NET MVC