Entity Framework Core 10 Essentials
Model a database with EF Core, create a DbContext, query with LINQ, and persist inserts and updates with SaveChangesAsync.
Part 1: What You Will Learn
Model a database with EF Core, create a DbContext, query with LINQ, and persist inserts and updates with SaveChangesAsync.
- Create an entity class and a DbContext.
- Configure a SQLite database provider.
- Add and query entities asynchronously.
- Understand how change tracking lets EF Core generate UPDATE statements.
Project setup: Create a .NET 10 Console App and install `Microsoft.EntityFrameworkCore.Sqlite`. For real projects, use EF Core migrations instead of `EnsureCreated()` once the schema begins to evolve.
Part 2: Topic-Specific Working Example
The following example is written specifically for this lesson. Create the project described above, enter the code, run it, and then change some values to observe how the feature behaves.
using Microsoft.EntityFrameworkCore;
public sealed class Product
{
public int Id { get; set; }
public required string Name { get; set; }
public decimal Price { get; set; }
}
public sealed class ShopDbContext : DbContext
{
public DbSet<Product> Products => Set<Product>();
protected override void OnConfiguring(
DbContextOptionsBuilder options)
{
options.UseSqlite("Data Source=shop.db");
}
}
await using ShopDbContext db = new();
await db.Database.EnsureCreatedAsync();
Product product = new()
{
Name = "USB-C Hub",
Price = 129.90m
};
db.Products.Add(product);
await db.SaveChangesAsync();
List<Product> expensiveProducts = await db.Products
.Where(p => p.Price >= 100m)
.OrderBy(p => p.Name)
.ToListAsync();
foreach (Product item in expensiveProducts)
{
Console.WriteLine($"{item.Id}: {item.Name} - {item.Price:C}");
}
// Change tracking detects this modification.
product.Price = 119.90m;
await db.SaveChangesAsync();Part 3: How the Code Works
- `DbSet<Product>` represents the Products table from the application's point of view.
- `UseSqlite()` selects the SQLite provider and connection string.
- LINQ expressions are translated into SQL by the provider where possible.
- After an entity is tracked, changing a property and calling `SaveChangesAsync()` produces the appropriate database update.
Part 4: Mini Project & Practice
Mini project: create a Student entity with StudentId, Name, Course, and Mark. Add five records, query students with marks above 70, update one mark, and delete one student.
Tip: Type the code yourself in Visual Studio 2026, run it, then deliberately change one part at a time. The goal is to understand the feature rather than simply copy the finished example.
When you are comfortable with this lesson, continue to Lesson 24.
C# in Visual Studio 2026
📘 This lesson is part of the book C# in Visual Studio 2026 by Dr. Liew Voon Kiong.
View on Amazon Kindle Edition