Covers declaring indexes in EF Core (HasIndex, [Index], IsUnique, HasFilter, IsDescending, IncludeProperties), how they reach SQL Server through migrations, and the non-sargable LINQ patterns (ToLower, Contains, date parts, implicit conversions) that defeat them.
In EF Core, indexes are part of the model: HasIndex(...) or the [Index] attribute generate CREATE INDEX in a migration, so the schema stays in source control. EF Core adds indexes for foreign keys by convention; every other index is your decision. On SQL Server you can make them unique, filtered (HasFilter), descending (IsDescending) and covering (IncludeProperties). The other half is writing LINQ that can use them: Name.ToLower() == x, Contains (becomes LIKE '%x%'), o.CreatedAt.Year == 2026 and arithmetic on columns are non-sargable, so SQL Server scans; an nvarchar parameter against a varchar column causes an implicit conversion. I verify with the actual execution plan and Query Store. The trade-off: every index speeds some reads and slows every write.
"I treat indexes as part of the EF Core model. I declare them in the entity configuration with
HasIndex, or the[Index]attribute for simple cases, and the migration creates them. That way the index is reviewed with the query that needs it and every environment gets the same schema. EF Core already creates an index for each foreign key by convention, which covers joins, but the indexes that matter for performance, the ones matching your WHERE and ORDER BY, are your job.On SQL Server, EF Core exposes the useful options.
IsUnique()enforces a business rule like one active email per tenant.HasFilter(\"[DeletedAt] IS NULL\")gives a smaller filtered index, which is how you do a unique index that ignores soft-deleted rows.IncludePropertiesadds non-key columns so a projection is covered without key lookups, andIsDescendinghelps queries that sort newest first on a composite key. I design them from the actual query: equality columns first, then the range or sort column, then included columns for what theSelectreturns.The part people miss is that LINQ can translate and still defeat the index.
c.Email.ToLower() == emailbecomesLOWER([c].[Email]) = @email, which SQL Server can't seek on, and with the default case-insensitive collation theToLowerwas never needed.Contains(term)becomesLIKE '%term%', which always scans.o.CreatedAt.Year == 2026becomesDATEPART(year, ...), and the fix is a range. A mapping mismatch, like avarcharcolumn EF Core thinks is Unicode, makes EF Core send annvarcharparameter and SQL Server converts the column on every row. The mistake I see is adding indexes without checking the plan. I always confirm a seek in the actual plan and watch Query Store after release."
| API | SQL | Use for |
|---|---|---|
HasIndex(e => e.Email) / [Index(nameof(Email))] |
CREATE INDEX |
Lookups and joins |
.IsUnique() |
CREATE UNIQUE INDEX |
Business keys |
.HasFilter("[DeletedAt] IS NULL") |
... WHERE [DeletedAt] IS NULL |
Soft delete, sparse status values |
.IsDescending(false, true) |
(TenantId ASC, CreatedAt DESC) |
Newest-first lists |
.IncludeProperties(e => new { e.Name, e.Total }) |
INCLUDE (Name, Total) |
Covering a projection |
.HasDatabaseName("IX_...") |
Index name | Stable names for scripts and monitoring |
| LINQ | SQL | Sargable fix |
|---|---|---|
c.Email.ToLower() == email |
LOWER([c].[Email]) = @email |
Compare directly (case-insensitive collation) or store a normalised column |
p.Name.Contains(term) |
LIKE N'%' + @term + N'%' |
StartsWith (LIKE 'x%') or full-text search |
o.CreatedAt.Year == 2026 |
DATEPART(year, [o].[CreatedAt]) = 2026 |
o.CreatedAt >= start && o.CreatedAt < end |
o.Total * 1.1m > 100 |
Arithmetic on the column | Move the arithmetic to the parameter |
varchar column mapped as Unicode |
CONVERT_IMPLICIT on the column |
.IsUnicode(false) or HasColumnType("varchar(50)") |
A login lookup [in a system I worked on] used Email.ToLower() == input against 3 million users and scanned the table: about 250 ms and 40,000 logical reads per login. Removing ToLower() (the collation was already case-insensitive) and adding a unique filtered index on Email turned it into a seek: under 2 ms and 4 reads.
Checks that the candidate keeps indexes in the EF Core model, knows the SQL Server index options EF Core exposes, and can spot LINQ that translates but cannot use an index.
Green flags
HasIndex and knows FK indexes are created by conventionRed flags
ToLower() for case-insensitive comparisons by defaultEntity configuration migration SQL Server
HasIndex(...).IsUnique() -> CreateIndex(name, table, -> CREATE UNIQUE INDEX
.HasFilter(...) columns, unique, [IX_Users_Email]
filter) ON [Users]([Email])
WHERE [DeletedAt] IS NULL
The index is stored in the model snapshot, so removing it from the configuration generates a DropIndex. Index names follow IX_{Table}_{Columns} unless you set HasDatabaseName.
A B-tree index is sorted by the column's stored value. A seek works only when SQL Server can compute a range of keys from the predicate. LOWER([Email]) = @p asks about a value that isn't stored, so SQL Server must compute LOWER for every row: a scan. The same applies to DATEPART, CONVERT and arithmetic. Predicates that can use a seek are called sargable (Search ARGument ABLE).
SQL Server and Azure SQL databases typically use a case-insensitive collation such as SQL_Latin1_General_CP1_CI_AS, so = already ignores case. ToLower() is then pure cost. If you do need case-insensitive search on a case-sensitive column, add a computed, persisted, normalised column with its own index.
EF Core maps string to nvarchar by default. If the real column is varchar but the model doesn't say so, EF Core sends @p nvarchar(4000). Because nvarchar has higher data type precedence, SQL Server converts the column (CONVERT_IMPLICIT), and depending on collation that can turn a seek into a scan. The plan shows a warning on the SELECT operator. Fix the model with IsUnicode(false) and a max length so parameters match.
WHERE TenantId = @t AND Status = @s AND CreatedAt >= @from
ORDER BY CreatedAt DESC
SELECT Id, Total, CustomerName
-> key: (TenantId, Status, CreatedAt DESC) INCLUDE (Total, CustomerName)
Equality columns first, then the range or sort column; include what the projection returns to avoid key lookups. Every index costs write time, storage and log, so check sys.dm_db_index_usage_stats for unused ones.
ToQueryString() and run it with the actual plan: look for Index Seek vs Scan, Key Lookup and conversion warnings.Users table with 1 million rows, query with and without ToLower(), and compare logical reads with SET STATISTICS IO ON.varchar column without IsUnicode(false), run a lookup and find the CONVERT_IMPLICIT warning in the plan..Year == 2026 filter as a range and compare plans.IncludeProperties for a projection and watch the Key Lookup disappear.Index configuration in EF Core 10 and the sargable rewrites of common queries.
namespace Shop.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
public sealed class Order
{
public int Id { get; set; }
public int TenantId { get; set; }
public OrderStatus Status { get; set; }
public DateTime CreatedAt { get; set; }
public decimal Total { get; set; }
public required string CustomerName { get; set; }
public required string Reference { get; set; } // varchar(20) in the database
}
public enum OrderStatus { Open, Paid, Shipped, Cancelled }
public sealed class OrderConfiguration : IEntityTypeConfiguration<Order>
{
public void Configure(EntityTypeBuilder<Order> b)
{
b.Property(o => o.CustomerName).HasMaxLength(200);
b.Property(o => o.Reference).HasMaxLength(20).IsUnicode(false); // avoids CONVERT_IMPLICIT
// Matches: WHERE TenantId = @t AND Status = @s ORDER BY CreatedAt DESC, projecting Total and CustomerName.
b.HasIndex(o => new { o.TenantId, o.Status, o.CreatedAt })
.IsDescending(false, false, true)
.IncludeProperties(o => new { o.Total, o.CustomerName })
.HasDatabaseName("IX_Orders_Tenant_Status_CreatedAt");
// Business key, unique per tenant.
b.HasIndex(o => new { o.TenantId, o.Reference }).IsUnique();
}
}
public sealed class OrderSearch(ShopDbContext db)
{
// Non-sargable: DATEPART on the column.
// db.Orders.Where(o => o.CreatedAt.Year == year)
// Sargable: a half-open range on the stored value.
public Task<List<int>> InYearAsync(int tenantId, int year, CancellationToken ct)
{
var from = new DateTime(year, 1, 1);
var to = from.AddYears(1);
return db.Orders
.Where(o => o.TenantId == tenantId && o.CreatedAt >= from && o.CreatedAt < to)
.Select(o => o.Id)
.ToListAsync(ct);
}
// Non-sargable: o.Reference.ToLower() == reference.ToLower(); the CI collation already ignores case.
public Task<Order?> ByReferenceAsync(int tenantId, string reference, CancellationToken ct) =>
db.Orders.FirstOrDefaultAsync(o => o.TenantId == tenantId && o.Reference == reference, ct);
}
-- Generated by the migration
CREATE INDEX [IX_Orders_Tenant_Status_CreatedAt]
ON [Orders] ([TenantId], [Status], [CreatedAt] DESC)
INCLUDE ([Total], [CustomerName]);
CREATE UNIQUE INDEX [IX_Orders_TenantId_Reference] ON [Orders] ([TenantId], [Reference]);
ToLower() on both sides for case-insensitive matching. Why it is wrong: it wraps the column in LOWER(), forcing a scan, and the default collation is already case-insensitive. Instead: compare directly, or add a normalised persisted column with an index.Contains for search on a large table. Why it is wrong: LIKE '%x%' cannot seek. Instead: use StartsWith where it fits, or SQL Server full-text search or Azure AI Search..Year, .Date or .Month. Why it is wrong: the column is wrapped in a date function. Instead: filter on a half-open range.varchar columns mapped as Unicode. Why it is wrong: EF Core sends nvarchar parameters and SQL Server converts the column. Instead: IsUnicode(false) with a max length.Indexes belong with the queries that need them, so I want them in the EF Core model and in the same pull request as the query. The deeper skill is reading the generated SQL for sargability: EF Core will happily translate a predicate that SQL Server cannot seek on. I keep a short list of patterns to flag in review (ToLower, Contains, date parts, arithmetic on columns, Unicode mismatches) and check new hot queries in the actual plan before merging. After release, Query Store tells me if a plan regressed.
Two things people forget. First, filtered indexes and parameters: SQL Server only uses a filtered index if it can prove at compile time that the query's predicate falls inside the filter. A global query filter like DeletedAt == null becomes a literal IS NULL and matches, but Status == status becomes @status and usually does not, because the cached plan has to work for any value; use a constant (EF.Constant in EF Core 8+) where it matters. Second, indexes have a running cost: every insert and update maintains them, so I review sys.dm_db_index_usage_stats (seeks and scans versus updates) and drop indexes nobody reads. Fragmentation matters less on modern SSD storage than it used to, but random GUID keys still cause page splits and low page density, so I watch sys.dm_db_index_physical_stats and prefer sequential keys. Azure SQL automatic tuning can suggest or create indexes; I let it recommend, then review and move the good ones into the EF Core model so the snapshot stays the source of truth.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Composite index with INCLUDE | Hot, stable query shapes | Write overhead, storage | Rarely run queries |
| Filtered index | Sparse values, soft delete, unique among active rows | Must match the filter predicate; parameterised filters may not use it | Predicates that vary |
| Persisted computed column + index | Normalised search keys | Extra column and write cost | When a direct comparison already works |
| Full-text or Azure AI Search | Free-text Contains search |
Separate infrastructure | Exact-match lookups |
Because the generated SQL applies the function to every row (LOWER([c].[Email]) = @email, DATEPART(year, [o].[PlacedAt]) = 2026), so SQL Server can't seek an index on the raw column. It scans the whole index instead, which costs CPU and reads proportional to the table and gets worse as data grows. Fixes: express dates as a half-open range (WHERE [o].[PlacedAt] >= @start AND [o].[PlacedAt] < @end); rely on the database's case-insensitive collation instead of ToLower(), so no function is needed at all; or index a persisted computed column when you really need the derived value.
An nvarchar(max) column cannot be a key column of a B-tree index (clustered or non-clustered); it can only sit in INCLUDE or a full-text index, so a lookup on it scans. Values that do not fit in the row (over 8,000 bytes) move to LOB pages, so reading them costs extra I/O, and online index operations were historically restricted. The optimiser also estimates row size from the declared type, assuming a max column is about half-full of a large value, so sorts and hash joins get oversized memory grants that waste memory and reduce concurrency. EF Core maps an unconfigured string to nvarchar(max), so the fix is to give strings realistic lengths with HasMaxLength, a convention, or [MaxLength], and keep max for genuine documents.
SQL Server uses a filtered index only if it can prove at compile time that the query's predicate implies the index filter. It fails when: the filter value is a parameter (WHERE Status = @status), because the cached plan must work for any value; the predicate is written differently from the filter (an OR, a function, a different column expression) so the optimiser can't match it; the index doesn't cover the query and a scan looks cheaper on the cost estimate; or statistics on the filtered index are stale (they update on modifications to the filtered rows only, so they can lag). In EF Core, keep global query filters as simple literals (DeletedAt == null becomes IS NULL), use EF.Constant (EF Core 8+) where a fixed value matters, include the projected columns, and verify the seek in the actual plan.
How to tell it (STAR)
**S:** Our login endpoint in [the identity service] slowed to around [300 ms] at p95 and Azure SQL CPU was high every morning. **T:** I was asked to bring login latency back under [50 ms] without scaling the database. **A:** Query Store showed the user lookup as the top CPU consumer. The actual plan was a full scan because the LINQ called ToLower on the email, which became LOWER on the column, and the collation was already case-insensitive. I removed the ToLower, added a unique filtered index through an EF Core migration, and added the pattern to our review checklist. **R:** The lookup went from about [40,000] logical reads to [4], login p95 dropped to around [20 ms], and database CPU at peak fell by roughly [a third].
Last updated 23 Nov 2026.