EF Core setup and DbContext
EF Core is the official ORM of .NET: it maps C# classes to tables, turns LINQ into SQL and hands rows back as objects. This note covers the setup: provider package, model, DbContext, AddDbContext, conventions and Code First vs Database First.
51.1 The problem: SQL is just a string
- With raw ADO.NET (Microsoft.Data.Sqlite) the SQL lives inside a C# string; the compiler never checks it.
- Here Price is misspelled as Prise: the build succeeds, the app crashes at runtime.
- Every column is read by index (GetInt32(0), GetString(1)) and mapped to an object by hand.
C#
using Microsoft.Data.Sqlite;using var conn = new SqliteConnection( "Data Source=shop.db");conn.Open();var cmd = conn.CreateCommand();cmd.CommandText = "SELECT Id, Name, Prise FROM Products";using var reader = cmd.ExecuteReader();var products = new List<Product>();while (reader.Read()) products.Add(new Product(reader.GetInt32(0), reader.GetString(1), reader.GetInt32(2)));Console.WriteLine($"Products: {products.Count}"); record Product(int Id, string Name, int Price);Output
$ dotnet run raw.csUnhandled exception.Microsoft.Data.Sqlite.SqliteException (0x80004005):SQLite Error 1: 'no such column: Prise'.51.2 The ORM idea
- ORM = Object Relational Mapper: it does the C# <-> database translation for you.
- One class = one table, one object = one row, one property = one column.
- You write LINQ; EF Core translates it to SQL through a provider and returns objects.
- Step 1
1.Class -> Table (Product -> Products)
- Step 2
2.Object -> Row (one product = one row)
- Step 3
3.Property -> Column (Price -> "Price")
- Step 4
4.LINQ -> SQL (EF Core translates)
EF Core = the official ORM of .NET
51.3 Install a provider package
- EF Core does not talk to a database by itself: every database has its own provider package.
- The course uses SQLite: just a file, no separate server to install.
- Switching to SQL Server or PostgreSQL changes only the provider package; the EF code stays almost the same.
Terminal
dotnet add package \ Microsoft.EntityFrameworkCore.Sqlite # SQL Server:# Microsoft.EntityFrameworkCore.SqlServer# PostgreSQL:# Npgsql.EntityFrameworkCore.PostgreSQLOutput
$ dotnet add package Microsoft.EntityFrameworkCore.Sqliteinfo : PackageReference for package 'Microsoft.EntityFrameworkCore.Sqlite' version '10.0.14' added to file 'Shop.csproj'.51.4 Model, DbContext and AddDbContext
- Step 1, the model (entity): a plain C# class. Name is required, Description is nullable, NewProduct is only the POST body.
- Step 2, the DbContext: your session with the database. It takes options in the constructor, so the database choice stays outside the class.
- DbSet<Product> represents the Products table: you query and add through it.
- Step 3, registration: connection string in appsettings.json, AddDbContext + UseSqlite in Program.cs.
C#
public class Product{ public int Id { get; set; } public required string Name { get; set; } public int Price { get; set; } public string? Description { get; set; }} public record NewProduct(string Name, int Price);C#
using Microsoft.EntityFrameworkCore; public class ShopDbContext( DbContextOptions<ShopDbContext> options) : DbContext(options){ public DbSet<Product> Products => Set<Product>();}C#
using Microsoft.EntityFrameworkCore; var builder = WebApplication.CreateBuilder(args); // appsettings.json:// "ConnectionStrings": {// "Shop": "Data Source=shop.db" }var cs = builder.Configuration .GetConnectionString("Shop");builder.Services.AddDbContext<ShopDbContext>( options => options.UseSqlite(cs)); var app = builder.Build();- AddDbContext registers the DbContext as scoped by default: every HTTP request gets its own fresh DbContext.
- Step 1
1.dotnet add package ...EntityFrameworkCore.Sqlite
- Step 2
2.Write the entity: Product
- Step 3
3.ShopDbContext with DbSet<Product>
- Step 4
4.AddDbContext + UseSqlite(connection string)
- Step 5
5.Endpoint gets ShopDbContext injected (scoped)
- Step 6
6.LINQ -> SQL -> rows -> Product objects
51.5 Creating the database: EnsureCreated
- The DbContext is scoped, so after Build() you open a DI scope to get one.
- EnsureCreated checks whether the database exists; if not, it builds the whole schema from the model.
- The logs show the CREATE TABLE that EF Core generated.
C#
var app = builder.Build(); using (var scope = app.Services.CreateScope()){ var db = scope.ServiceProvider .GetRequiredService<ShopDbContext>(); db.Database.EnsureCreated();}Output
$ dotnet run --no-launch-profile --urls http://localhost:5051info: Microsoft.EntityFrameworkCore.Database.Command[20101] Executed DbCommand (1ms) [Parameters=[], ...] CREATE TABLE "Products" ( "Id" INTEGER NOT NULL CONSTRAINT "PK_Products" PRIMARY KEY AUTOINCREMENT, "Name" TEXT NOT NULL, "Price" INTEGER NOT NULL, "Description" TEXT NULL );info: Microsoft.Hosting.Lifetime[14] Now listening on: http://localhost:505151.6 Conventions: schema from names
| In the model | In the schema |
|---|---|
| public int Id | Primary key, AUTOINCREMENT in SQLite |
| required string Name | TEXT NOT NULL |
| int Price | INTEGER NOT NULL |
| string? Description | TEXT NULL (nullable allows NULL) |
| DbSet<Product> Products | Table name "Products" |
- No table or column name was written anywhere: conventions decided all of it.
- To change a convention, override it with attributes or the Fluent API (next video).
51.7 Reading and saving with the DbContext
- Inject ShopDbContext straight into a minimal API endpoint as a parameter.
- ToListAsync turns the rows of Products into a List<Product>.
- Add only tells the DbContext "this is new"; SaveChangesAsync sends the real INSERT.
- EF builds a parameterized INSERT and sets the new Id on the object via RETURNING.
C#
app.MapGet("/products", async (ShopDbContext db) => await db.Products.ToListAsync()); app.MapPost("/products", async ( NewProduct input, ShopDbContext db) =>{ var product = new Product { Name = input.Name, Price = input.Price }; db.Products.Add(product); await db.SaveChangesAsync(); return TypedResults.Created( $"/products/{product.Id}", product);});Output
$ curl -i localhost:5051/products \ -H "Content-Type: application/json" \ -d '{"name":"Mixer Grinder","price":2499}'HTTP/1.1 201 CreatedLocation: /products/1{"id":1,"name":"Mixer Grinder","price":2499, "description":null}Output
info: Microsoft.EntityFrameworkCore.Database.Command[20101] Executed DbCommand (26ms) [Parameters=[@p0='?', @p1='?' (Size = 13), @p2='?' (DbType = Int32)] INSERT INTO "Products" ("Description", "Name", "Price") VALUES (@p0, @p1, @p2) RETURNING "Id";51.8 Checkpoint: an entity without Id
- Coupon has no Id; Code is the unique value. EnsureCreated throws: no primary key found by convention.
- EF Core cannot track an entity without a key. Fix: put [Key] on Code (or call HasNoKey for a keyless type).
C#
public class Coupon{ public required string Code { get; set; } public int Discount { get; set; }}Output
$ dotnet run nokey.csUnhandled exception. System.InvalidOperationException:The entity type 'Coupon' requires a primary keyto be defined. If you intended to use a keylessentity type, call 'HasNoKey' in 'OnModelCreating'. # [Key] public required string Code ...$ dotnet run nokey-fixed.csCreated51.9 Comparison: Code First vs Database First
| Point | Code First | Database First |
|---|---|---|
| Direction | Classes -> database | Database -> classes |
| Tool | Migrations (or EnsureCreated in demos) | dotnet ef dbcontext scaffold |
| Best for | New projects (what we did here) | An existing / legacy database |
51.10 Common mistakes
- Injecting a DbContext into a singleton: a DbContext is not thread safe and is a short-lived unit of work; in development the app fails at startup with the captive dependency error.
- Fix: make the service scoped too, so every request gets a fresh DbContext.
- Believing EnsureCreated keeps the schema in sync: after adding Stock it sees the table exists and does nothing, so GET returns 500.
- Hardcoding the connection string in code instead of appsettings / user secrets.
C#
// Wrong: captive DbContextbuilder.Services.AddSingleton<ProductService>();// Cannot consume scoped service// 'ShopDbContext' from singleton// 'ProductService'. // Right: every request gets a new DbContextbuilder.Services.AddScoped<ProductService>(); public class ProductService(ShopDbContext db){ public Task<int> CountAsync() => db.Products.CountAsync();}Output
# restart, shop.db already exists (Stock added to Product)info: Microsoft.EntityFrameworkCore.Database.Command[20101] SELECT COUNT(*) FROM "sqlite_master" WHERE "type" = 'table' AND "rootpage" IS NOT NULL;# no CREATE TABLE, no ALTER TABLE $ curl -i localhost:5051/productsHTTP/1.1 500 Internal Server Errorfail: Microsoft.EntityFrameworkCore.Query[10100] Microsoft.Data.Sqlite.SqliteException (0x80004005): SQLite Error 1: 'no such column: p.Stock'.51.11 Rules for EF Core setup
- Keep the connection string in appsettings or user secrets, never in code.
- Register with AddDbContext and inject it only into scoped services.
- Pick the correct provider package for your database.
- Follow conventions, e.g. name the key Id.
- Keep SQL logs on in development; use migrations instead of EnsureCreated in real apps.
51.12 Interview tips
- EF Core is the .NET ORM: it maps classes to tables and translates LINQ to SQL through a provider.
- DbContext = unit of work: connection, change tracking and SaveChanges; registered as scoped with AddDbContext.
- Conventions: Id becomes the primary key, nullability decides NULL / NOT NULL, the DbSet name becomes the table name.
- Say you check the generated SQL in the logs and use migrations (not EnsureCreated) for schema changes.