Skip to main content
C# Fundamentals for Beginners to Advanced
CHAPTER 27 Beginner

Entity Framework Core Basics

Updated: May 17, 2026
5 min read

# CHAPTER 27

Entity Framework Core Basics

1. Introduction

In Chapter 25, we used ADO.NET. We wrote literal SQL strings ("SELECT * FROM Users") inside our C# code. This is error-prone, hard to maintain, and vulnerable to SQL injection.

Entity Framework Core (EF Core) is a modern Object-Relational Mapper (ORM). It allows you to interact with your database using 100% C# objects and LINQ. EF Core automatically translates your C# code into highly optimized, secure SQL commands behind the scenes.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Understand what an ORM is.
  • Map a C# Class (Model) to a database table.
  • Create a DbContext class.
  • Understand Code-First Migrations.
  • Perform CRUD operations using C# and LINQ.

3. The Model (The Table Blueprint)

In EF Core, a database table is represented by a standard C# Class. The properties become the table columns.
csharp
1234567
// This class will become a 'Products' table in SQL
public class Product
{
    public int Id { get; set; } // EF Core automatically makes properties named 'Id' the Primary Key!
    public string Name { get; set; }
    public decimal Price { get; set; }
}

4. The DbContext (The Database Session)

The DbContext is the bridge between your C# application and the database. It holds DbSet properties, which represent the actual tables.
csharp
1234567891011121314
using Microsoft.EntityFrameworkCore;

public class AppDbContext : DbContext
{
    // This tells EF Core: "Create a table called Products to hold Product objects"
    public DbSet<Product> Products { get; set; }

    // Configure the database connection
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        // Using a local SQLite database for simplicity
        optionsBuilder.UseSqlite("Data Source=app.db"); 
    }
}

5. Migrations (Creating the Database)

In the "Code-First" approach, you write the C# classes first, and EF Core generates the SQL database for you.

In your terminal, you run:

  1. 1. dotnet ef migrations add InitialCreate (Analyzes your C# classes and creates a blueprint).
  1. 2. dotnet ef database update (Executes the blueprint, actually creating the database file/tables).

6. Performing CRUD Operations

Once the database exists, you interact with it using standard C# syntax. No SQL strings required!
csharp
12345678910111213141516171819202122232425262728
using System;
using System.Linq;

class Program
{
    static void Main()
    {
        using (var db = new AppDbContext())
        {
            // CREATE (Insert)
            var newProduct = new Product { Name = "Laptop", Price = 999.99m };
            db.Products.Add(newProduct);
            db.SaveChanges(); // Actually sends the INSERT SQL to the database

            // READ (Select using LINQ!)
            var product = db.Products.FirstOrDefault(p => p.Name == "Laptop");
            Console.WriteLine($"Found: {product.Name} for ${product.Price}");

            // UPDATE
            product.Price = 850.00m;
            db.SaveChanges(); // Detects the change and sends an UPDATE SQL

            // DELETE
            db.Products.Remove(product);
            db.SaveChanges(); // Sends a DELETE SQL
        }
    }
}

7. Why use EF Core over ADO.NET?

  • Type Safety: If you rename a property from Price to Cost, the C# compiler ensures all your queries update. With raw SQL strings, you wouldn't know it was broken until runtime.
  • Security: EF Core automatically uses parameterized queries, making SQL injection impossible.
  • Productivity: Writing .Add() and .SaveChanges() takes 2 seconds. Writing standard SQL insert logic in ADO.NET takes 15 lines of code.

8. Common Mistakes

  • Forgetting .SaveChanges(): You can .Add() 100 items to the DbSet, but absolutely nothing happens in the actual database until you explicitly call db.SaveChanges().
  • Querying inside a loop (N+1 Problem): Running a LINQ query to the database inside a foreach loop will execute hundreds of separate SQL commands, crashing server performance. Fetch the data once into a List, then loop.

9. Best Practices

  • Use EF Core's Asynchronous methods (SaveChangesAsync, ToListAsync) in web applications to prevent freezing the server threads during database I/O.

10. Exercises

  1. 1. Define a Student class with Id, Name, and Grade properties.
  1. 2. Create a SchoolContext class inheriting from DbContext containing a DbSet<Student> Students.

11. MCQs with Answers

Question 1

What does ORM stand for?

Q2. What is the primary purpose of EF Core? a) To design UIs b) To allow developers to interact with relational databases using C# objects instead of raw SQL strings c) To host websites Answer: b) To allow developers to interact with databases using C# objects

Q3. In the EF Core "Code-First" approach, what determines the database schema? a) The SQL Server Administrator b) Your C# Models (Classes) c) An XML file Answer: b) Your C# Models (Classes)

Question 4

Which EF Core class acts as the main bridge/session between your code and the database?

Question 5

Inside the DbContext, what property type represents a database table?

Question 6

What happens if a C# Model has a property named Id?

Question 7

What feature analyzes your C# models and generates the commands to update the SQL database structure?

Question 8

What command actually sends your changes (Inserts, Updates, Deletes) to the database?

Question 9

Which technology does EF Core use to query the database using C# syntax?

Question 10

How does EF Core handle SQL Injection?

12. Interview Questions

  • Q: Explain the Code-First vs Database-First approach in EF Core.
  • Q: What is the N+1 Query Problem in Entity Framework, and how do you solve it using .Include() (Eager Loading)?
  • Q: Explain the role of the DbContext.

13. Summary

Entity Framework Core bridges the gap between Object-Oriented C# and Relational SQL Databases. By mapping classes to tables (DbSet), using Migrations to create schemas, and leveraging LINQ for queries, EF Core massively increases developer productivity and security.

14. Next Chapter Recommendation

You have reached the end of the technical chapters! In Chapter 28: C# Interview Preparation, we will review the most critical theoretical concepts, testing your readiness for a professional C# backend developer interview.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·