TExcelTAD
Home › ASP.NET Core › Querying with LINQ

Querying with LINQ

With EF Core you read data by writing LINQ against a DbSet<T>. The important difference from LINQ over a List<T> is that a DbSet<T> is an IQueryable<T>: your query is not run in C# but translated to SQL and executed by the database. This lesson continues the blog API from the previous lessons.

A first query

csharp
app.MapGet("/posts", async (AppDbContext db, int page = 1, int size = 10) =>
    await db.Posts
        .AsNoTracking()
        .Where(p => p.PublishedOn <= DateTime.UtcNow)
        .OrderByDescending(p => p.PublishedOn)
        .Skip((page - 1) * size)
        .Take(size)
        .Select(p => new PostSummary(p.Id, p.Title, p.Blog.Title))
        .ToListAsync());

record PostSummary(int Id, string Title, string Blog);

Turn on SQL logging ("Microsoft.EntityFrameworkCore.Database.Command": "Information" in appsettings.Development.json) and call it:

bash · try it yourself
$ curl -s "localhost:5000/posts?page=1&size=2"
[{"id":7,"title":"Truing a wheel","blog":"Bike Repairs"},{"id":6,"title":"Sourdough starter, day 5","blog":"Kitchen Notes"}]

The console of the running app shows the single SQL statement EF Core produced:

text
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (1ms) [Parameters=[@__UtcNow_0='?' (DbType = DateTime), @__p_2='?' (DbType = Int32), @__p_1='?' (DbType = Int32)], CommandType='Text', CommandTimeout='30']
      SELECT "p"."Id", "p"."Title", "b"."Title" AS "Blog"
      FROM "Posts" AS "p"
      INNER JOIN "Blogs" AS "b" ON "p"."BlogId" = "b"."Id"
      WHERE "p"."PublishedOn" <= @__UtcNow_0
      ORDER BY "p"."PublishedOn" DESC
      LIMIT @__p_2 OFFSET @__p_1

Notice three things: only the three selected columns are fetched, the join to Blogs was added automatically because the projection used p.Blog.Title, and paging happens in the database with LIMIT/OFFSET.

The same query over memory

The LINQ operators are the same ones you know from C#. This runnable version applies them to an in-memory list so you can see the result shape:

csharp · try it yourself
using System;
using System.Collections.Generic;
using System.Linq;

var blogs = new List<Blog> { new(1, "Kitchen Notes"), new(2, "Bike Repairs") };
var posts = new List<Post>
{
    new(1, "Knife skills", new DateTime(2026, 9, 1), 1),
    new(2, "Chain cleaning", new DateTime(2026, 9, 3), 2),
    new(3, "Perfect rice", new DateTime(2026, 9, 10), 1),
    new(4, "Brake pads", new DateTime(2026, 9, 18), 2),
    new(5, "Draft: soup", new DateTime(2026, 12, 1), 1),
};
var today = new DateTime(2026, 10, 16);

IEnumerable<string> Page(int page, int size) => posts
    .Where(p => p.PublishedOn <= today)
    .OrderByDescending(p => p.PublishedOn)
    .Skip((page - 1) * size)
    .Take(size)
    .Join(blogs, p => p.BlogId, b => b.Id, (p, b) => 
quot;{p.Id} {p.Title} [{b.Title}]"); Console.WriteLine("Page 1: " + string.Join(" | ", Page(1, 2))); Console.WriteLine("Page 2: " + string.Join(" | ", Page(2, 2))); var third = Page(3, 2).ToList(); Console.WriteLine("Page 3: " + (third.Count == 0 ? "(empty)" : string.Join(" | ", third))); var perBlog = posts.GroupBy(p => p.BlogId) .Select(g => new { Blog = blogs.Single(b => b.Id == g.Key).Title, Count = g.Count() }); foreach (var row in perBlog) Console.WriteLine(
quot;{row.Blog}: {row.Count} posts"); record Blog(int Id, string Title); record Post(int Id, string Title, DateTime PublishedOn, int BlogId);
Page 1: 4 Brake pads [Bike Repairs] | 3 Perfect rice [Kitchen Notes]
Page 2: 2 Chain cleaning [Bike Repairs] | 1 Knife skills [Kitchen Notes]
Page 3: (empty)
Kitchen Notes: 3 posts
Bike Repairs: 2 posts

Deferred execution

Building a query does not run it. Nothing happens until you enumerate it — with ToListAsync, FirstOrDefaultAsync, CountAsync, foreach, and so on. That lets you add filters conditionally:

csharp
IQueryable<Post> query = db.Posts;
if (blogId is not null) query = query.Where(p => p.BlogId == blogId);
if (search is not null) query = query.Where(p => p.Title.Contains(search));
var results = await query.ToListAsync();   // one SQL statement with both filters

The same rule holds in-memory, which this program makes visible by logging each time the filter runs:

csharp · try it yourself
using System;
using System.Collections.Generic;
using System.Linq;

var titles = new List<string> { "Knife skills", "Chain cleaning", "Perfect rice" };

var query = titles.Where(t =>
{
    Console.WriteLine(
quot; checking {t}"); return t.Contains("i"); }); Console.WriteLine("Query built, nothing ran yet"); titles.Add("Brake pads"); // added AFTER the query was defined var list = query.ToList(); // runs now Console.WriteLine(
quot;Matched: {string.Join(", ", list)}");
Query built, nothing ran yet
  checking Knife skills
  checking Chain cleaning
  checking Perfect rice
  checking Brake pads
Matched: Knife skills, Chain cleaning, Perfect rice

Reading single items

Method Returns when no row When several rows match
FindAsync(id) null (checks tracked entities first) — (by key)
FirstOrDefaultAsync(pred) null First one
SingleOrDefaultAsync(pred) null Throws
FirstAsync(pred) Throws First one
csharp
app.MapGet("/posts/{id:int}", async (int id, AppDbContext db) =>
    await db.Posts.FindAsync(id) is { } post ? Results.Ok(post) : Results.NotFound());

Tracking vs. no-tracking

By default, entities returned by a query are tracked so SaveChanges can detect edits. For read-only endpoints add AsNoTracking(): it skips the snapshot bookkeeping and is faster. Projections with Select into DTOs are never tracked.

Bulk updates and deletes

EF Core 7+ can update or delete many rows with a single statement, without loading them first:

csharp
int archived = await db.Posts
    .Where(p => p.PublishedOn < new DateTime(2020, 1, 1))
    .ExecuteDeleteAsync();

await db.Posts
    .Where(p => p.BlogId == 2)
    .ExecuteUpdateAsync(s => s.SetProperty(p => p.Title, p => p.Title + " (archived)"));

Note: ExecuteUpdate/ExecuteDelete run immediately and bypass the change tracker, so already-loaded entities are not updated in memory.

Things that do not translate

EF Core can only translate expressions it understands. Calling your own C# method inside Where fails at runtime with an InvalidOperationException ("could not be translated"). Either rewrite it with translatable operations or switch to client-side evaluation explicitly with AsEnumerable() after filtering as much as possible in the database.

Tip: Always filter and page in the database. db.Posts.ToList().Where(...) downloads the entire table first.

Test yourself

When is the SQL for db.Posts.Where(p => p.BlogId == 1) executed?

  1. When Where is called
  2. When the DbContext is created
  3. When the query is enumerated, e.g. by ToListAsync()
  4. When SaveChanges is called

What does AsNoTracking() do?

  1. Returns entities the change tracker will not watch, making reads cheaper
  2. Disables SQL logging
  3. Prevents the query from using indexes
  4. Deletes tracked entities

Which method throws if more than one row matches?

  1. FirstOrDefaultAsync
  2. FindAsync
  3. Take(1)
  4. SingleOrDefaultAsync