Entity Framework Core Beginner

What is EF Core?

Entity Framework Core (EF Core) lets you work with a database using C# classes and LINQ instead of writing SQL by hand. This lesson explains what an ORM is, the main EF Core pieces (entities, DbContext, DbSet, providers) and how a LINQ query becomes SQL.

Where EF Core sits in an MVC app
  1. ControllerAsks for data: db.Products.Where(p => p.Price < 500)
  2. DbContextYour gateway to the database, with a DbSet per table
  3. EF Core and the providerTranslates LINQ to SQL for SQL Server, PostgreSQL, SQLite...
  4. DatabaseRuns the SQL and returns rows
  5. EntitiesEF Core turns the rows back into C# objects

The idea in plain words

Your app thinks in objects (a Product with a Name and a Price); the database thinks in tables and rows. An ORM (object-relational mapper) translates between the two. With EF Core you write C# classes called entities, describe them in a DbContext, and query with LINQ. EF Core generates the SQL, runs it, and gives you objects back.

EF Core works with many databases through providers, such as Microsoft.EntityFrameworkCore.SqlServer, Npgsql for PostgreSQL and Microsoft.EntityFrameworkCore.Sqlite. You can start from code and create the database with migrations (code first), or generate classes from an existing database (scaffolding).

Example: entity, context and a query

C#
public class Product
{
    public int Id { get; set; }              // primary key by convention
    public string Name { get; set; } = "";
    public decimal Price { get; set; }
}

public class ShopContext : DbContext
{
    public ShopContext(DbContextOptions<ShopContext> options) : base(options) { }

    public DbSet<Product> Products => Set<Product>();
}

// In a controller or service
var cheap = await db.Products
    .Where(p => p.Price < 500)
    .OrderBy(p => p.Name)
    .ToListAsync();

What EF Core sends to SQL Server

You never write this SQL, but it helps to know what happens. Values are sent as parameters.

SQL
SELECT [p].[Id], [p].[Name], [p].[Price]
FROM [Products] AS [p]
WHERE [p].[Price] < 500.0
ORDER BY [p].[Name]

Common mistakes

  • Thinking EF Core removes the need to understand SQL. Knowing SQL helps you write efficient queries.
  • Calling ToList() too early and filtering in memory instead of in the database.
  • Using one DbContext instance for the whole app; it should be short-lived, usually one per request.

Interview question

What is the role of DbContext in EF Core?

DbContext represents a session with the database. It exposes DbSet properties for querying and saving entities, tracks changes to the entities it loads, translates LINQ queries to SQL through the configured provider, and writes changes back in a transaction when SaveChanges is called. It is meant to be short-lived, typically one instance per web request, and is not thread-safe.

Your progress is saved only in this browser.

Want the full details? Read the official Microsoft documentation for this topic.