Sub topic 7
Reading Data with LINQ Queries
Your database now has Blogs and Posts tables. This chapter shows how to read rows back out of them using LINQ, the query language built into C#. You will filter rows, sort them, pick single items, count them, page through them, and choose which columns to load.
What a LINQ Query Is
LINQ (Language Integrated Query) is a set of C# methods for asking questions about collections. You have probably used it on lists, like numbers.Where(n => n > 5).
EF Core lets you write the same kind of query against a DbSet. A DbSet is the property on your DbContext that stands for a table, such as db.Blogs. EF Core does not run your C# code against the table. It reads your query, translates it into SQL (the language databases understand), sends the SQL to the database, and turns the returned rows into C# objects.
Some Data to Query
The examples use the Blog, Post, and BloggingContext classes from the earlier chapters. This Program.cs adds a few rows first so the queries have something to find. Adding data is covered fully in the next chapter. For now, just run it.
using Microsoft.EntityFrameworkCore;
using var db = new BloggingContext();
if (!db.Blogs.Any())
{
var cooking = new Blog { Url = "https://example.com/cooking" };
cooking.Posts.Add(new Post { Title = "Bread", Content = "Flour and water" });
cooking.Posts.Add(new Post { Title = "Soup", Content = "Hot and tasty" });
var travel = new Blog { Url = "http://travel.example.org" };
travel.Posts.Add(new Post { Title = "Rome", Content = "Old streets" });
var music = new Blog { Url = "https://music.example.net" };
db.Blogs.AddRange(cooking, travel, music);
db.SaveChanges();
}
Console.WriteLine($"Blogs in database: {db.Blogs.Count()}");Filtering with Where
Where keeps only the rows that match a condition. The condition is a lambda, which is a small inline function written with =>.
var httpsBlogs = db.Blogs
.Where(b => b.Url.StartsWith("https://"))
.ToList();
foreach (var blog in httpsBlogs)
{
Console.WriteLine(blog.Url);
}EF Core turns this into SQL similar to SELECT ... FROM "Blogs" WHERE "Url" LIKE 'https://%'. The filtering happens inside the database, so only matching rows travel to your program.
You can combine conditions with && (and) and || (or), or chain several Where calls:
var someBlogs = db.Blogs
.Where(b => b.Url.Contains("example"))
.Where(b => b.BlogId > 1)
.ToList();Sorting with OrderBy
OrderBy sorts from smallest to largest. OrderByDescending sorts the other way. Use ThenBy to break ties.
var sortedPosts = db.Posts
.OrderBy(p => p.BlogId)
.ThenBy(p => p.Title)
.ToList();When the Query Actually Runs
Building a query does not touch the database. The variable below holds a description of a query, called an IQueryable:
IQueryable<Blog> query = db.Blogs.Where(b => b.Url.Contains("example"));The SQL runs only when you ask for results. This is called deferred execution. These methods run the query:
| Method | What it returns | If nothing matches |
|---|---|---|
| `ToList()` | All matching rows as a list | An empty list |
| `First()` | The first matching row | Throws an exception |
| `FirstOrDefault()` | The first matching row | Returns `null` |
| `Single()` | The only matching row | Throws (also throws if more than one) |
| `SingleOrDefault()` | The only matching row | Returns `null` (throws if more than one) |
| `Count()` | How many rows match | `0` |
| `Any()` | `true` if at least one row matches | `false` |
| `foreach` loop | Each row, one at a time | The loop body never runs |
Deferred execution lets you build a query step by step, for example adding a filter only when the user typed a search word:
string? search = "cook";
IQueryable<Blog> blogQuery = db.Blogs;
if (!string.IsNullOrEmpty(search))
{
blogQuery = blogQuery.Where(b => b.Url.Contains(search));
}
var results = blogQuery.OrderBy(b => b.BlogId).ToList();The value of search is sent to the database as a parameter. EF Core never pastes it into the SQL text, which protects you from SQL injection.
Getting One Row
To find one row, use First, FirstOrDefault, or Single with a condition:
var cookingBlog = db.Blogs.FirstOrDefault(b => b.Url.Contains("cooking"));
if (cookingBlog is null)
{
Console.WriteLine("Not found");
}
else
{
Console.WriteLine($"Found blog {cookingBlog.BlogId}");
}To look up a row by its primary key, Find is shorter:
var blogOne = db.Blogs.Find(1);Find first checks whether the context already loaded that row, and only queries the database if it did not. It returns null when no row has that key.
Counting and Checking
Count and Any ask the database for a number or a yes/no answer. They do not load the rows.
int postCount = db.Posts.Count(p => p.BlogId == 1);
bool hasEmptyPosts = db.Posts.Any(p => p.Content == "");
Console.WriteLine($"{postCount} posts, any empty: {hasEmptyPosts}");Prefer Any() over Count() > 0 when you only need to know whether a row exists. The database can stop at the first match.
Paging with Skip and Take
Skip jumps over some rows and Take limits how many come back. Together they split results into pages.
int pageNumber = 2;
int pageSize = 2;
var page = db.Posts
.OrderBy(p => p.PostId)
.Skip((pageNumber - 1) * pageSize)
.Take(pageSize)
.ToList();Always sort before paging. Otherwise a row might appear on two pages or on none.
Choosing Columns with Select
Loading whole entities brings back every column. Select lets you pick only what you need. This is called projection. The result can be an anonymous type, which is a small unnamed object created with new { ... }.
var titles = db.Posts
.Where(p => p.Blog.Url.StartsWith("https://"))
.Select(p => new { p.Title, BlogUrl = p.Blog.Url })
.ToList();
foreach (var t in titles)
{
Console.WriteLine($"{t.Title} from {t.BlogUrl}");
}The navigation property p.Blog here is turned into a SQL join, so EF Core reads the blog's URL without loading full Blog objects. Relationships get their own chapter later.
Things That Can Go Wrong
The query cannot be translated
EF Core can translate only methods it knows into SQL. If you call your own C# method inside Where, the database has no idea what it means:
static bool IsShort(string url) => url.Length < 20;
// Throws InvalidOperationException: the LINQ expression could not be translated.
var shortBlogs = db.Blogs.Where(b => IsShort(b.Url)).ToList();Fix it by writing the condition directly (b.Url.Length < 20, which EF Core can translate), or by loading the rows first with ToList() and filtering in memory. Filtering in memory loads every row, so use that only for small tables.
Text comparisons follow database rules
Whether "Cooking" matches "cooking" depends on the database, not on C#. In SQLite, Contains is case-sensitive, while some other databases ignore case by default. Test your searches against the database you really use.
Calling ToList too early
// Loads every post, then filters in memory
var slow = db.Posts.ToList().Where(p => p.BlogId == 1).ToList();
// Filters in the database
var fast = db.Posts.Where(p => p.BlogId == 1).ToList();Both give the same result, but the first one moves the whole table into memory. Put ToList() at the end.
Exercise
Write a query that returns the titles of the posts belonging to blog 1, sorted alphabetically, as a List<string>.
Show answer
var postTitles = db.Posts.Where(p => p.BlogId == 1).OrderBy(p => p.Title).Select(p => p.Title).ToList(); Where filters in the database, OrderBy sorts, Select loads only the Title column, and ToList runs the query.
Exercise
You run db.Blogs.Single(b => b.Url.Contains("example")) and it throws an exception, even though matching blogs exist. Why, and what could you use instead?
Show answer
Single throws when more than one row matches, and all three sample blogs contain "example". Use First (with an OrderBy) to take one of them, or use a more specific condition so that only one row matches.
Exercise
At which line does the database receive SQL? Line 1: var q = db.Blogs.Where(b => b.BlogId > 1); Line 2: q = q.OrderBy(b => b.Url); Line 3: var n = q.Count();
Show answer
Line 3. Lines 1 and 2 only build an IQueryable. Count is a method that runs the query, so it sends a SELECT COUNT(*) statement with the filter.