Sub topic 7
Reading Data with LINQ Queries
You have a database with Blogs and Posts tables. This chapter shows how to read rows from those tables using C# code instead of SQL.
What LINQ Is
LINQ (Language Integrated Query) is a set of C# methods for asking questions about data. Examples are Where, OrderBy, and Select. You may already use LINQ on lists in memory.
EF Core lets you call the same methods on a DbSet. EF Core does not run your C# against every row. It translates your query into SQL. A query is a request for data. The database runs the SQL and sends back only the rows you asked for.
A Worked Example
This program uses the BloggingContext from earlier chapters. It adds some blogs first so the queries have data to return.
using var db = new BloggingContext();
db.Blogs.AddRange(
new Blog { Url = "https://example.com/cats" },
new Blog { Url = "https://example.com/dogs" },
new Blog { Url = "https://other.org/birds" });
db.SaveChanges();
// Filter: keep only matching rows
var exampleBlogs = db.Blogs
.Where(b => b.Url.Contains("example"))
.ToList();
// Sort: order rows by a column
var sorted = db.Blogs
.OrderBy(b => b.Url)
.ToList();
// Single result: get the first match
var first = db.Blogs
.OrderBy(b => b.BlogId)
.First(b => b.Url.EndsWith("dogs"));
// Projection: pick only the columns you need
var urls = db.Blogs
.Select(b => b.Url)
.ToList();
Console.WriteLine($"Example blogs: {exampleBlogs.Count}");
Console.WriteLine($"First sorted: {sorted[0].Url}");
Console.WriteLine($"Dogs blog id: {first.BlogId}");
Console.WriteLine(string.Join(", ", urls));Here is what each method does:
| Method | Meaning | SQL it becomes |
|---|---|---|
| `Where` | Filter. Keep only rows that match a rule. | `WHERE` |
| `OrderBy` | Sort rows from smallest to largest. | `ORDER BY` |
| `Select` | Projection. Choose which values to return. | the column list after `SELECT` |
| `First` | Return the first row. Throws an error if there is none. | `LIMIT 1` |
| `ToList` | Run the query and put the results in a list. | (runs the SQL) |
When the Query Runs
Methods like Where and OrderBy only build the query. Nothing goes to the database yet. This is called deferred execution, which means the query waits until you ask for results. Calls like ToList, First, Count, or a foreach loop send the SQL to the database.
Exercises
Exercise
Write a query that returns the URLs of all blogs starting with "https://", sorted by URL, as a List<string>.
Show answer
var list = db.Blogs.Where(b => b.Url.StartsWith("https://")).OrderBy(b => b.Url).Select(b => b.Url).ToList();
Exercise
In the code var q = db.Blogs.Where(b => b.BlogId > 1);, has any SQL been sent to the database yet? Why or why not?
Show answer
No. Where only builds the query. The SQL runs when you call a method like ToList, First, or Count, or when you loop over q with foreach.