Skip to content
Tutorials Center
My learning

Topics

Lesson 2 of 41 ยท Getting Started

Your First EF Core App

Build a first EF Core console app with SQLite - install packages, define an entity and a DbContext, create the database, add and query rows - plus a runnable stand-in.

The fastest way to understand EF Core is to build something tiny. In this lesson you create a console app that stores books in a SQLite file, adds a few rows and reads them back. SQLite needs no server, so it is ideal for learning. The real EF Core code below is read-only on this site (the runner has no NuGet), so follow it in your own terminal; then run the stand-in editors to see the same flow with an in-memory fake.

You will meet the three types every EF Core program has: an entity class, a DbContext, and the code that uses them. Later lessons explain each in depth (DbContext and DbSet, conventions).

Create the project and add packages

Install the .NET SDK, then run these commands in an empty folder:

Terminal
dotnet new console -n BookShop
cd BookShop
dotnet add package Microsoft.EntityFrameworkCore.Sqlite
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet tool install --global dotnet-ef

Microsoft.EntityFrameworkCore.Sqlite is the provider (it pulls in the core package). Design is needed by the dotnet ef command-line tool, which you will use for migrations in the Migrations chapter. Use the EF Core version that matches your .NET version (EF Core 10 goes with .NET 10).

Define the entity and the context

An entity is a plain class. By convention a property called Id becomes the primary key.

C#
public class Book
{
    public int Id { get; set; }
    public string Title { get; set; } = "";
    public decimal Price { get; set; }
    public int Pages { get; set; }
}

The context represents a session with the database. Each DbSet<T> property is a table you can query.

C#
using Microsoft.EntityFrameworkCore;

public class ShopContext : DbContext
{
    public DbSet<Book> Books => Set<Book>();

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

UseSqlite chooses the provider and the connection string. Other providers have their own UseXxx method (Providers and connection strings).

Create the database, insert and query

Put this in Program.cs:

C#
using var db = new ShopContext();
db.Database.EnsureCreated();          // creates shop.db and the Books table

db.Books.Add(new Book { Title = "Learning EF", Price = 24.90m, Pages = 320 });
db.Books.Add(new Book { Title = "SQL in Practice", Price = 18m, Pages = 210 });
db.SaveChanges();                      // runs the INSERT statements

var cheap = db.Books
    .Where(b => b.Price < 20m)
    .OrderBy(b => b.Title)
    .ToList();

foreach (var b in cheap)
{
    Console.WriteLine($"{b.Id}: {b.Title} ({b.Price})");
}

Run it with dotnet run. The first run creates the file and prints 2: SQL in Practice (18). A second run adds two more books (ids 3 and 4), because nothing clears the table.

Three things happened that you did not write: EF Core inferred the table Books and its columns from the class, generated INSERT statements when you called SaveChanges, and translated the Where/OrderBy chain into a single SELECT. EnsureCreated is fine for demos, but real projects use migrations, because EnsureCreated cannot evolve an existing schema.

Nothing is sent to the database until you call SaveChanges() (for writes) or enumerate the query with ToList(), foreach or First() (for reads). This is called deferred execution, and it explains most "why did that run twice" surprises.

See the generated SQL

Add one line to OnConfiguring to log SQL to the console:

C#
options.UseSqlite("Data Source=shop.db").LogTo(Console.WriteLine);

You will see commands like INSERT INTO "Books" ("Pages", "Price", "Title") VALUES (@p0, @p1, @p2) RETURNING "Id";. Exact text and parameter types vary by provider and version, so treat it as a debugging aid, not a contract.

Stand-in: a tiny DbContext

The editor below is a stand-in, not EF Core. It reproduces the shape of the API: a context with sets, Add, SaveChanges that "writes" pending rows, and LINQ queries over the saved data.

C# Stand-in: a mini DbContext with SaveChanges

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Notice that Id was filled in by "the database" during SaveChanges. Real EF Core does the same: after saving, the entity's key property holds the generated value (Keys and generated values).

Stand-in: what SaveChanges sends

A second stand-in prints the SQL a tiny "provider" would run for pending changes. It is simplified and not the exact text EF Core produces.

C# Stand-in: pending changes become SQL

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Common first-run mistakes

  • Forgetting SaveChanges: Add only marks the entity as pending. Nothing reaches the database.
  • Mismatched package versions: mixing EF Core 8 and 10 packages causes odd runtime errors. Keep them on one version.
  • Using EnsureCreated and migrations together: pick one. Once you use migrations, never call EnsureCreated.
  • Not disposing the context: wrap it in using (or let dependency injection do it) so the connection is released.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which package do you add to use EF Core with SQLite?

    The provider package Microsoft.EntityFrameworkCore.Sqlite includes EF Core itself and the SQLite support.
  2. 2. When are INSERT statements actually sent to the database?

    Add only tracks the entity as pending. SaveChanges executes the commands.
  3. 3. What primary key does EF Core assume for a property named Id?

    A property named Id or TypeNameId is picked up as the primary key by convention.
  4. 4. Why prefer migrations over EnsureCreated in real projects?

    EnsureCreated only creates a database from scratch. Migrations record schema changes so they can be applied step by step.

Summary

  • A minimal app needs a provider package, an entity class and a DbContext with DbSet<T> properties.
  • UseSqlite("Data Source=...") configures the provider and connection.
  • Add queues changes; SaveChanges executes them; queries run when you enumerate them.
  • EnsureCreated is for demos; use migrations for anything real.
  • The editors here are stand-ins that mirror the flow, not EF Core.

Next: From Objects to Tables: the Mapping Idea