skip to content

LINQ Querying

How EF Core runs LINQ against a database: translation to SQL and its limits, raw SQL and set-based updates, and global query filters. Interviewers check that you know where a query really executes.

part ofEntity Framework Coreread it →
on this pageshow

explore

questions

18

In EF Core 10, how do you hide soft-deleted forum posts from every query with HasQueryFilter, and how does a moderator page still see them?

level: juniorimportance: must knowfreq 55%

answer

  1. configured once in OnModelCreating
  2. an extra Where on every query of the type
  3. applies to navigations and Include too
  4. IgnoreQueryFilters() per query
  5. deleting still needs IsDeleted = true

basics

~10 s

Configure modelBuilder.Entity<Post>().HasQueryFilter(p => !p.IsDeleted) in OnModelCreating; EF adds that condition to every query of Post, including Include and navigations. A moderator query calls IgnoreQueryFilters() to switch filters off for that one query.

solid answer

~40 s

A global query filter is a predicate attached to an entity type in the model: `modelBuilder.Entity<Post>().HasQueryFilter(p => !p.IsDeleted)`. EF Core then adds it, like an extra `Where`, to every LINQ query that reaches `Post` — `db.Posts`, a `Post` loaded through `Include`, a navigation used in a projection, `FromSql` on the `DbSet`, even `ExecuteUpdate`. A moderator page that must list deleted posts adds `.IgnoreQueryFilters()` to its query, which disables the filters for every entity type in that query. The filter only hides rows: deleting a post still means setting `IsDeleted = true` and saving, usually by converting `Remove` into an update in a `SaveChanges` override or interceptor. An index that covers the `IsDeleted` condition keeps the extra predicate cheap.

code

csharp · 7 lines
csharp
app.MapGet("/mod/threads/{id:int}/deleted", async (int id, ForumDbContext db, CancellationToken ct) =>
    await db.Posts
        .IgnoreQueryFilters()
        .Where(p => p.ThreadId == id && p.IsDeleted)
        .OrderByDescending(p => p.DeletedAt)
        .ToListAsync(ct))
    .RequireAuthorization("Moderator");

go deeper

for a junior

Recall HasQueryFilter in OnModelCreating for soft delete and IgnoreQueryFilters() for the one query that needs deleted rows.

for a middle

Explain that the filter belongs to the entity type, so it also applies to Include, navigations and FromSql, and that IgnoreQueryFilters is query-wide.

for a senior

Design the write side, indexes and unique constraints around soft delete, and make every bypass explicit and authorized.

for a principal

Decide whether soft delete is worth its cost per aggregate, and how retention and hard purges fit legal and storage needs.

## What a global query filter is A **global query filter** is a boolean predicate attached to an entity type in the EF Core model. Whenever a query touches that entity type, EF adds the predicate as if you had written an extra `Where`. You configure it once, in `OnModelCreating` or an `IEntityTypeConfiguration<T>`, with `HasQueryFilter`. On a multi-tenant discussion forum, deleted posts stay in the table so moderators can restore them: ```csharp public class Post { public int Id { get; set; } public int ThreadId { get; set; } public string Body { get; set; } = ""; public bool IsDeleted { get; set; } public DateTime? DeletedAt { get; set; } } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Post>().HasQueryFilter(p => !p.IsDeleted); } ``` Now `await db.Posts.Where(p => p.ThreadId == threadId).ToListAsync()` sends SQL whose `WHERE` clause contains both the thread condition and `NOT (p."IsDeleted")`. ## Where the filter applies The filter belongs to the entity type, not to the `DbSet`, so it is applied wherever EF builds a query over `Post`: - queries rooted at `db.Posts` or `db.Set<Post>()`; - posts loaded through `Include(t => t.Posts)` on a thread; - navigations used inside projections, such as `t.Posts.Count()`; - queries that start with `FromSql` on `db.Posts`; - `ExecuteUpdate` and `ExecuteDelete` over `db.Posts`, which only touch rows the filter lets through. It does **not** reach SQL that EF does not build from the model: `Database.SqlQuery<T>`, `Database.ExecuteSql`, or plain ADO.NET. ## Turning it off for one query A moderation screen calls `IgnoreQueryFilters()`: ```csharp var deleted = await db.Posts .IgnoreQueryFilters() .Where(p => p.IsDeleted && p.DeletedAt > since) .ToListAsync(ct); ``` Two details matter: 1. `IgnoreQueryFilters()` is **query-wide**: it disables the filters of every entity type the query touches, including included and navigated ones, not only `Post`. 2. It is opt-out per query. There is no setting on the context that disables filters for all queries, which is deliberate: bypassing must be visible at the call site. ## Writing the deletion The filter only hides rows. Something must still set the flag: | Approach | How it works | |---|---| | Explicit update | `post.IsDeleted = true; post.DeletedAt = now; await db.SaveChangesAsync();` | | Convert removals | override `SaveChangesAsync` or use an interceptor to turn `Deleted` entries of soft-deletable types into `Modified` with the flag set | | Bulk | `db.Posts.Where(...).ExecuteUpdateAsync(s => s.SetProperty(p => p.IsDeleted, true))` | Converting removals lets the rest of the code call `db.Posts.Remove(post)` as usual. ## How the filter appears in SQL Because the filter is added during translation, it shows up in the generated SQL like any other predicate, and `ToQueryString()` displays it. For the thread query above the `WHERE` clause holds both conditions, combined with `AND`. Two consequences follow: - The database can use an index that covers both conditions, so the filter does not have to cost a scan. - A filter that EF cannot translate makes **every** query on the type fail, so keep filters to simple property comparisons. ## Practical notes - The filter costs a predicate on every query. A partial index on non-deleted rows, or a composite index that includes `IsDeleted`, keeps it cheap. - Unique constraints must account for deleted rows: a deleted post's slug may block a new one unless the index excludes deleted rows. - A filter is part of the model, so it is the same for every query; behaviour that varies per request needs a context-level value, covered by tenant filters.

  • Does IgnoreQueryFilters() on db.Threads.Include(t => t.Posts) also show deleted posts?
    Yes. `IgnoreQueryFilters()` applies to the whole query, so the filters of every entity type in it are switched off, including the `Post` filter on the included collection. To keep a different filter active, EF Core 10's named filters let you ignore only selected filters.
  • Why doesn't HasQueryFilter by itself make db.Posts.Remove(post) a soft delete?
    The filter only shapes queries; it says nothing about writes. `Remove` marks the entry `Deleted`, and `SaveChanges` sends a `DELETE`. To soft-delete, set `IsDeleted` explicitly or intercept deleted entries before saving and switch them to `Modified` with the flag set.

A soft-delete filter is like a library that keeps withdrawn books on a staff-only shelf: every catalogue search skips that shelf automatically, and only a librarian who explicitly asks for staff access sees those books again.

  • HasQueryFilter physically deletes rows marked IsDeleted.
  • The filter applies only to queries that start from db.Posts.
  • IgnoreQueryFilters() removes the filter for the rest of the context's life.
  • Database.SqlQuery<T> results are filtered by HasQueryFilter too.
  • Calling Remove on a filtered entity soft-deletes it automatically.

Assumes EF Core 10; HasQueryFilter and the parameterless IgnoreQueryFilters() behave as in EF Core 8 and 9, while ignoring individual named filters is new in EF Core 10.

open as a page

In EF Core 10, how does FromSql run a raw SQL query with a user-supplied value, and what can you compose on top of it?

level: juniorimportance: must knowfreq 58%

basics

~20 s

Call db.Readings.FromSql($"SELECT ... WHERE "DeviceId" = {deviceId}"): FromSql takes a FormattableString and sends each interpolated value as a DbParameter, never as SQL text. LINQ after it wraps your SQL as a subquery, and results are tracked entities.

open as a page

To archive millions of old sensor readings in EF Core 10, why use ExecuteUpdateAsync or ExecuteDeleteAsync instead of load-modify-SaveChanges, and what do they bypass?

level: middleimportance: must knowfreq 57%

basics

~20 s

ExecuteUpdateAsync and ExecuteDeleteAsync turn a LINQ query into one SQL UPDATE or DELETE that runs immediately, without loading or tracking rows, and return the affected row count. They bypass the change tracker, SaveChanges, its concurrency checks and any implicit transaction.

open as a page

In EF Core 10, what happens when a query calls a C# method EF cannot translate, inside Where versus inside the final Select?

level: middleimportance: must knowfreq 64%

basics

~20 s

Inside Where, EF Core throws an InvalidOperationException saying the expression could not be translated. Inside the final Select it fetches the needed columns and runs the method on the client: only the top-level projection may be client-evaluated.

open as a page

An EF Core 10 project dashboard loads each project's work items and members in one query and has become slow; how do AsSplitQuery and QuerySplittingBehavior help, and what do they cost?

level: seniorimportance: must knowfreq 55%

basics

~10 s

Loading two sibling collections in one SQL statement multiplies rows per project. AsSplitQuery, or UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery) globally, sends one statement per collection instead, at the cost of extra round trips and no single-snapshot consistency.

open as a page

In EF Core, how do you see the SQL a LINQ query will send without running it, and where does ToQueryString fall short?

level: juniorimportance: should knowfreq 42%

basics

~20 s

Call ToQueryString() on the IQueryable before executing it: it compiles the query and returns the SQL with its parameter values, for debugging only. It cannot show terminal operators like CountAsync, and for a split query it shows just the first statement.

open as a page

In EF Core 10, how do named query filters let a query skip the soft-delete filter but keep the tenant filter on forum posts?

level: middleimportance: should knowfreq 34%

basics

~10 s

EF Core 10 lets you register several filters per entity type under keys, HasQueryFilter("SoftDelete", ...) and HasQueryFilter("Tenant", ...), and IgnoreQueryFilters(["SoftDelete"]) disables only that one. Before 10, a second unnamed call overwrote the first.

open as a page

In EF Core 10, how do you map a database view without a primary key, and what can a keyless entity type not do?

level: middleimportance: should knowfreq 33%

basics

~20 s

Declare the class as a keyless entity type with [Keyless] or HasNoKey(), map it with ToView("device_daily_stats"), and expose a DbSet to query it. EF never tracks, inserts, updates or deletes it, and migrations do not create the view.

open as a page

In EF Core 10, what does Database.SqlQuery<T> return for scalars and for unmapped classes, and why must a composed scalar column be named Value?

level: middleimportance: should knowfreq 38%

basics

~20 s

Database.SqlQuery<T> runs parameterized SQL and maps each row to a scalar or to any class with a property per column, even one outside the model. It returns an untracked IQueryable<T>; composed scalar queries read a column named Value.

open as a page

In an EF Core 10 app on PostgreSQL, how do you call a stored procedure that archives sensor readings and a function that returns readings?

level: middleimportance: should knowfreq 40%

basics

~20 s

A procedure that returns no rows runs through Database.ExecuteSqlAsync($"CALL archive_readings({cutoff})"), which returns an int. A function returning reading rows is queried with db.SensorReadings.FromSql($"SELECT * FROM readings_over({deviceId}, {limit})") and, being a SELECT, can be composed with LINQ.

open as a page

In EF Core 10, which GroupBy queries translate to a SQL GROUP BY, and what happens when a query returns the groups themselves?

level: middleimportance: should knowfreq 44%

basics

~20 s

GroupBy followed by a Select of the key and aggregates such as Count or Sum becomes GROUP BY, and an aggregate filter becomes HAVING. A query ending in GroupBy is sent as an ordered SELECT and grouped on the client.

open as a page

In EF Core 10, how do you write a SQL LEFT JOIN in LINQ, and how did you have to express it before .NET 10?

level: middleimportance: should knowfreq 34%

basics

~20 s

Call the .NET 10 LeftJoin operator in method syntax, outer.LeftJoin(inner, outerKey, innerKey, (o, i) => ...), and EF Core 10 emits LEFT JOIN. Before .NET 10 you chained GroupJoin, SelectMany and DefaultIfEmpty in one exact shape.

open as a page

How would you test that an EF Core 10 tenant filter cannot leak another tenant's forum posts, including through code paths that skip filters?

level: seniorimportance: should knowfreq 28%

basics

~20 s

Seed two tenants in a real database, query through tenant A's context and assert no tenant B row appears via LINQ, Include, FromSql or ExecuteUpdate. Separately test paths filters never reach, like Database.SqlQuery, and every IgnoreQueryFilters call.

open as a page

An EF Core 10 forum page lists comments with Include(c => c.Post) and some comments vanish when their post is soft-deleted; why, and how do you fix it?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Comment.Post is required, so EF joins posts with an INNER JOIN, and the Post filter removes deleted posts from that join along with their comments. Add a matching Comment filter, or make the navigation optional so EF uses LEFT JOIN.

open as a page

In an EF Core 10 multi-tenant forum, why must a tenant query filter read a DbContext property rather than a value captured in OnModelCreating?

level: seniorimportance: should knowfreq 44%

basics

~20 s

OnModelCreating runs once and the model is cached, so a value captured there stays frozen for every later context. A filter reading a DbContext property, p => p.TenantId == TenantId, takes its value from the context running each query.

open as a page

In EF Core 10, when does FromSqlRaw open an SQL injection hole, and what do the EF1002 and EF1003 analyzer warnings catch?

level: seniorimportance: should knowfreq 46%

basics

~20 s

FromSqlRaw takes a plain string, so an interpolated or concatenated user value becomes SQL text and can inject. Pass values as {0} placeholders or DbParameter arguments instead. EF1002 warns on interpolation and EF Core 10's EF1003 on concatenation inside raw-SQL calls.

open as a page

After upgrading to EF Core 10, a query using ids.Contains(w.ProjectId) sends different SQL; what changed, and how do EF.Constant, EF.Parameter and UseParameterizedCollectionMode control it?

level: seniorimportance: should knowfreq 36%

basics

~20 s

EF Core 10 translates a captured collection into several scalar parameters, IN (@ids1, @ids2, ...), instead of EF 8-9's single JSON array parameter. UseParameterizedCollectionMode sets the default per context; EF.Constant, EF.Parameter and EF.MultipleParameters override it for one query.

open as a page

In EF Core 10, can a derived entity type such as Announcement carry its own query filter, and what do you do instead?

level: middleimportance: nice to knowfreq 20%

basics

~20 s

No. EF Core accepts query filters only on the root type of an inheritance hierarchy and throws for a derived type. Filter Post, which every Announcement query inherits, and put a type test inside that filter for subtype-only rules.

open as a page