Querying Data with LINQ

LINQ (Language Integrated Query) allows you to write expressive, readable queries directly in C# to interact with your database using EF Core.


What is LINQ?

LINQ integrates query capabilities into C# and .NET languages. EF Core translates LINQ queries into SQL at runtime, enabling you to work with strongly-typed objects.

There are two common LINQ syntaxes:

  • Method syntax: products.Where(p => p.Price < 50)
  • Query syntax: from p in products where p.Price < 50 select p

Basic LINQ Examples

1. Get All Products:
var all = context.Products.ToList();
2. Filter by Price:
var cheap = context.Products.Where(p => p.Price < 50).ToList();
3. Sort Products:
var sorted = context.Products.OrderByDescending(p => p.Price).ToList();
4. Select Specific Fields:
var names = context.Products.Select(p => p.Name).ToList();

Include Related Data

Use Include() to load navigation properties (e.g., one-to-many):

var categories = context.Categories
    .Include(c => c.Products)
    .ToList();

Grouping and Aggregate Functions

Use group by, Count(), Average(), and more:

var group = context.Products
    .GroupBy(p => p.CategoryId)
    .Select(g => new {
        CategoryId = g.Key,
        Count = g.Count(),
        AvgPrice = g.Average(p => p.Price)
    })
    .ToList();

Pagination with Skip and Take

var page = context.Products
    .Skip(10)
    .Take(10)
    .ToList();

LINQ provides a clean and efficient way to query databases in C#. Up next, we’ll focus on optimizing EF Core performance by managing tracking behavior, batching queries, and caching strategies.