Indexes and provider-specific tests
Indexes and provider-specific tests
Indexes help databases find or order records and can enforce uniqueness. They consume storage and increase write work. An EF Core model index is a schema intention; query plans and constraints in the actual database provide the evidence that it exists and is useful.
HasIndex declares an index and IsUnique requires unique indexed values according to provider comparison and NULL rules. A composite index has an ordered key sequence, so usefulness depends on filters, sort order and provider optimizer. Use actual migrations to install indexes in existing databases. Query plans reflect the current engine, statistics, data and parameter values; do not promise an index is chosen for every query. EXPLAIN QUERY PLAN is SQLite-specific and its output format may change. Inspect plan shape and results separately from timing. Use the actual production engine for translation, collation, transactions, migrations and constraint tests; SQLite is a useful relational test lane but is not SQL Server or PostgreSQL. EF InMemory is not a relational database. Value converters, owned and complex types and provider-specific functions require mapping and translation tests. Interceptors and logging can help inspect commands; avoid recording sensitive parameter values. The last fixture queries SQLite plan metadata only, not a benchmark.
Baseline: .NET 10 / C# 14, Microsoft.EntityFrameworkCore.Sqlite 10.0.15 (published package, restore and advisory checks pending). Each independent project includes its own complete source and project file. In an approved environment with a reviewed SDK and packages, restore from approved sources, then run dotnet build --no-restore and dotnet run --no-build in the fixture directory. Except for the migration-operation inspection, each uses its own open SQLite in-memory connection, synthetic catalog and schema created by EnsureCreated. No external database, account or credential is required. Expected results are reasoned, not executed.
Inspect a declared unique index
Read model metadata before relying on its schema intent.
using Microsoft.Data.Sqlite;using Microsoft.EntityFrameworkCore;using var connection = new SqliteConnection("Data Source=:memory:;Foreign Keys=True");connection.Open();var options = new DbContextOptionsBuilder<Catalog>().UseSqlite(connection).Options;using var db = new Catalog(options);db.Database.EnsureCreated();db.Categories.Add(new Category { Id = 1, Name = "Science" });db.Books.AddRange(new Book { Id = 1, Title = "Atlas", Stock = 4, CategoryId = 1 }, new Book { Id = 2, Title = "Comet", Stock = 0, CategoryId = 1 });db.SaveChanges();db.ChangeTracker.Clear();var index = db.Model.FindEntityType(typeof(Book))!.GetIndexes() .Single(i => i.Properties.SingleOrDefault()?.Name == nameof(Book.Title));Console.WriteLine(index.Properties.Single().Name);Console.WriteLine(index.IsUnique);class Book { public int Id { get; set; } public string Title { get; set; } = ""; public int Stock { get; set; } public int Revision { get; set; } = 1; public int CategoryId { get; set; } public Category? Category { get; set; }}class Category { public int Id { get; set; } public string Name { get; set; } = ""; public List<Book> Books { get; } = new();}class Catalog(DbContextOptions<Catalog> options) : DbContext(options) { public DbSet<Book> Books => Set<Book>(); public DbSet<Category> Categories => Set<Category>(); protected override void OnModelCreating(ModelBuilder model) { model.Entity<Book>().HasKey(b => b.Id); model.Entity<Book>().Property(b => b.Title).IsRequired(); model.Entity<Book>().Property(b => b.Revision).IsConcurrencyToken(); model.Entity<Book>().HasIndex(b => b.Title).IsUnique(); model.Entity<Book>().HasOne(b => b.Category).WithMany(c => c.Books) .HasForeignKey(b => b.CategoryId).OnDelete(DeleteBehavior.Restrict); }}Expected output (not executed):
TitleTrueThe declaration does not by itself prove an existing deployed schema matches it.
Verify duplicate title rejection
Attempt a second Atlas title using the same category.
using Microsoft.Data.Sqlite;using Microsoft.EntityFrameworkCore;using var connection = new SqliteConnection("Data Source=:memory:;Foreign Keys=True");connection.Open();var options = new DbContextOptionsBuilder<Catalog>().UseSqlite(connection).Options;using var db = new Catalog(options);db.Database.EnsureCreated();db.Categories.Add(new Category { Id = 1, Name = "Science" });db.Books.AddRange(new Book { Id = 1, Title = "Atlas", Stock = 4, CategoryId = 1 }, new Book { Id = 2, Title = "Comet", Stock = 0, CategoryId = 1 });db.SaveChanges();db.ChangeTracker.Clear();db.Books.Add(new Book { Title = "Atlas", Stock = 1, CategoryId = 1 });try { db.SaveChanges(); }catch (DbUpdateException) { Console.WriteLine("duplicate rejected"); }using var verify = new Catalog(options);Console.WriteLine(verify.Books.Count(b => b.Title == "Atlas"));class Book { public int Id { get; set; } public string Title { get; set; } = ""; public int Stock { get; set; } public int Revision { get; set; } = 1; public int CategoryId { get; set; } public Category? Category { get; set; }}class Category { public int Id { get; set; } public string Name { get; set; } = ""; public List<Book> Books { get; } = new();}class Catalog(DbContextOptions<Catalog> options) : DbContext(options) { public DbSet<Book> Books => Set<Book>(); public DbSet<Category> Categories => Set<Category>(); protected override void OnModelCreating(ModelBuilder model) { model.Entity<Book>().HasKey(b => b.Id); model.Entity<Book>().Property(b => b.Title).IsRequired(); model.Entity<Book>().Property(b => b.Revision).IsConcurrencyToken(); model.Entity<Book>().HasIndex(b => b.Title).IsUnique(); model.Entity<Book>().HasOne(b => b.Category).WithMany(c => c.Books) .HasForeignKey(b => b.CategoryId).OnDelete(DeleteBehavior.Restrict); }}Expected output (not executed):
duplicate rejected1The relational constraint prevents duplicate data even if a separate application check races.
Read a SQLite query plan without assuming exact wording
Use a parameterized plan query on the lab-owned connection. Count plan records, then separately verify matching rows.
using Microsoft.Data.Sqlite;using Microsoft.EntityFrameworkCore;using var connection = new SqliteConnection("Data Source=:memory:;Foreign Keys=True");connection.Open();var options = new DbContextOptionsBuilder<Catalog>().UseSqlite(connection).Options;using var db = new Catalog(options);db.Database.EnsureCreated();db.Categories.Add(new Category { Id = 1, Name = "Science" });db.Books.AddRange(new Book { Id = 1, Title = "Atlas", Stock = 4, CategoryId = 1 }, new Book { Id = 2, Title = "Comet", Stock = 0, CategoryId = 1 });db.SaveChanges();db.ChangeTracker.Clear();using var command = connection.CreateCommand();command.CommandText = "EXPLAIN QUERY PLAN SELECT Id FROM Books WHERE Title = $title";command.Parameters.AddWithValue("$title", "Atlas");using (var reader = command.ExecuteReader()) { int rows = 0; while (reader.Read()) rows++; Console.WriteLine(rows > 0);}Console.WriteLine(db.Books.Count(b => b.Title == "Atlas"));class Book { public int Id { get; set; } public string Title { get; set; } = ""; public int Stock { get; set; } public int Revision { get; set; } = 1; public int CategoryId { get; set; } public Category? Category { get; set; }}class Category { public int Id { get; set; } public string Name { get; set; } = ""; public List<Book> Books { get; } = new();}class Catalog(DbContextOptions<Catalog> options) : DbContext(options) { public DbSet<Book> Books => Set<Book>(); public DbSet<Category> Categories => Set<Category>(); protected override void OnModelCreating(ModelBuilder model) { model.Entity<Book>().HasKey(b => b.Id); model.Entity<Book>().Property(b => b.Title).IsRequired(); model.Entity<Book>().Property(b => b.Revision).IsConcurrencyToken(); model.Entity<Book>().HasIndex(b => b.Title).IsUnique(); model.Entity<Book>().HasOne(b => b.Category).WithMany(c => c.Books) .HasForeignKey(b => b.CategoryId).OnDelete(DeleteBehavior.Restrict); }}Expected output (not executed):
True1Plan rows exist; inspect their detail field in the intended environment to determine index use. This fixture intentionally does not assert a particular optimizer choice.
Apply the concept
Design a test matrix for migrating the catalog from SQLite to PostgreSQL. Include case-sensitive titles, uniqueness, transactions, concurrency tokens and query plans.
Use the manual practice and knowledge check to reason about the boundary. Do not apply these examples to a production database.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Indexes and provider-specific tests — knowledge check
Apply the lesson concepts to the following scenarios.
What does HasIndex configure?
Why test duplicate inserts against a real relational provider?
Does SQLite testing prove SQL Server translation?
Why might an index not be used?
What does EXPLAIN QUERY PLAN alone establish?