Lesson 8 — Beginner

Entity Framework Core for Beginners

.NETBeginnerC#Tutorial

Lesson 7 returned hard-coded balance data from memory. Real banking apps store millions of accounts on disk that survive server restarts. That long-term storage lives in a database — a digital filing cabinet optimized for finding and updating records fast.

Writing raw SQL for every feature works, but it gets repetitive. Entity Framework Core (EF Core) lets you use C# classes and LINQ queries instead — a translator between your objects and database tables.

What Is Entity Framework Core?

EF Core is an ORM (Object-Relational Mapper). It maps:

  • C# class → database table
  • Property → column
  • Object instance → row

Imagine a library where every book is labelled in English (C#) but the shelves are organised by Dewey Decimal (SQL). EF is the librarian who fetches and reshelves without you learning the entire cataloguing system — though learning basic SQL still helps later.

Core Pieces

Entity class — your C# model:

public class BankAccount
{
    public int Id { get; set; }
    public string OwnerName { get; set; } = "";
    public double Balance { get; set; }
}

DbContext — your database session:

public class AppDbContext : DbContext
{
    public DbSet<BankAccount> Accounts => Set<BankAccount>();

    protected override void OnConfiguring(DbContextOptionsBuilder options)
    {
        options.UseSqlite("Data Source=bank.db");
    }
}

DbSet represents a table. DbContext tracks changes and saves them when you call SaveChanges().

Create and Read Data

using var db = new AppDbContext();

// Create
db.Accounts.Add(new BankAccount
{
    OwnerName = "Priya Sharma",
    Balance = 15000
});
db.SaveChanges();

// Read
var account = db.Accounts.First(a => a.OwnerName == "Priya Sharma");
Console.WriteLine(account.Balance);

First is LINQ — a way to query collections with readable C# instead of SELECT * FROM Accounts WHERE... EF translates LINQ to SQL behind the scenes.

How EF Fits Your API

ASP.NET Core endpoint
      ↓
Injects AppDbContext
      ↓
LINQ query on Accounts
      ↓
EF generates SQL → SQLite/SQL Server
      ↓
Returns C# objects → JSON to mobile app

Your Lesson 7 API stops faking data. It reads real rows — the same pattern Netflix uses for watch history, just with different tables.

Migrations: Evolving the Schema

When you add a property like Email to BankAccount, the database table must gain a column. Migrations are versioned scripts EF generates:

dotnet ef migrations add AddEmailToAccount
dotnet ef database update

Think of migrations like tracked renovation plans for a building — each change is documented and repeatable across dev, test, and production.

Real-World Example

A food delivery startup stores restaurants, menus, and orders in SQL Server. Developers define Order, Customer, and MenuItem classes. EF handles inserting an order line and updating inventory counts in one transaction — so you do not charge a customer for a dish that sold out mid-checkout.

Common Misconceptions

"EF replaces SQL entirely." EF covers most CRUD. Report queries and performance tuning sometimes need raw SQL — that is normal.

"ORMs are always slow." Poorly written queries are slow in any stack. EF Core is fast when you query what you need and avoid loading entire tables accidentally.

"SQLite is only a toy." SQLite is perfect for learning and mobile/local apps. Production web apps often use SQL Server or PostgreSQL — EF switches with a connection string change.

"SaveChanges after every property edit." Batch changes in memory, then save once per logical operation — fewer round trips to the database.

Quick Recap

  • EF Core maps C# classes to database tables.
  • DbContext is the gateway for queries and saves.
  • LINQ expresses queries in C#; EF translates to SQL.
  • Migrations keep schema in sync with your models.
  • APIs + EF = persistent data for real applications.

Summary

Entity Framework Core is the bridge between your object-oriented C# world and relational databases underneath. Like WhatsApp syncing messages to a server instead of keeping them only on your phone, EF persists data beyond the lifetime of one request.

Lesson 9 introduces dependency injection — a clean way to hand your API a ready-to-use DbContext without constructing it manually everywhere.

Frequently Asked Questions

Microsoft's ORM for .NET that lets you work with databases using C# classes and LINQ instead of writing SQL for every operation.

Object-Relational Mapper — software that translates between C# objects and database tables so both sides stay in sync.

The central EF class representing a database session — you query DbSet properties and call SaveChanges() to persist updates.

EF handles most daily CRUD. Complex reports or tuning may still use raw SQL — EF supports both.

A generated script capturing schema changes (new columns, tables) so databases can be updated consistently across environments.

SQL Server, PostgreSQL, SQLite, MySQL, and more — install the matching EF provider NuGet package.

Key Takeaways

  • EF Core maps classes to tables so you query with C#.
  • DbContext and DbSet<T> are the main types to know.
  • SaveChanges() commits inserts and updates.
  • Migrations version your schema alongside code.
  • Pair EF with ASP.NET Core APIs for real persisted apps.

Suggested Next Reads

Share: LinkedIn Facebook X

Need help implementing this in your organization?

Contact Emerrank Consultancy