Insert and query related records with EF Core
EF Core maps .NET entities to database records and translates supported LINQ queries through a provider. A DbContext tracks changes until SaveChanges persists them.
This example inserts one collection and one related entry into SQLite. It uses a disposable in-memory database, so each run starts cleanly.
Create the project
Use the .NET 10 SDK and a matching EF Core 10 provider:
dotnet new console -n EfDemo -f net10.0
cd EfDemo
dotnet add package Microsoft.EntityFrameworkCore.Sqlite --version 10.0.0
Replace Program.cs:
using Microsoft.EntityFrameworkCore;
using var db = new NotesDb();
db.Database.OpenConnection();
db.Database.EnsureCreated();
db.Collections.Add(new Collection {
Name = "Reference", Entries = { new Entry { Title = "First note" } }
});
await db.SaveChangesAsync();
var titles = await db.Entries.OrderBy(x => x.Id).Select(x => x.Title).ToListAsync();
Console.WriteLine(string.Join(", ", titles));
public sealed class NotesDb : DbContext {
public DbSet<Collection> Collections => Set<Collection>();
public DbSet<Entry> Entries => Set<Entry>();
protected override void OnConfiguring(DbContextOptionsBuilder options)
=> options.UseSqlite("Data Source=:memory:");
}
public sealed class Collection {
public int Id { get; set; }
public string Name { get; set; } = "";
public List<Entry> Entries { get; set; } = [];
}
public sealed class Entry {
public int Id { get; set; }
public string Title { get; set; } = "";
public int CollectionId { get; set; }
public Collection Collection { get; set; } = null!;
}
Run dotnet run. Expect First note. EF assigns the generated key and relationship during saving.
Keep the context short-lived
The open connection keeps this in-memory database alive. A persistent application needs its real connection configuration and a deliberate schema-management strategy. EnsureCreated is for this isolated example, not an alternative to evolving a production schema with migrations. Do not share one context across concurrent operations. Use the latest compatible patch of the chosen EF Core major version when maintaining a real application.
Official references


Author: Herman Schoenfeld