wasAsked.

What is .Include()? Give an example.

Impetus · Role not specified · technical

Published

Year not specified · Entity Framework Core

Community answers

Posted by wasAsked editorial collection

Include() tells Entity Framework Core to load related entities in the same query — this is eager loading. Without it, navigation properties stay empty (unless you use lazy loading or load them separately). Example model public class Customer { public int Id { get; set; } public string Name { get; set; } = ""; public List<Order> Orders { get; set; } = []; } public class Order { public int Id { get; set; } public decimal Total { get; set; } public int CustomerId { get; set; } public Customer Customer { get; set; } = null!; public List<OrderItem> Items { get; set; } = []; } public class OrderItem { public int Id { get; set; } public int ProductId { get; set; } public Product Product { get; set; } = null!; public int Quantity { get; set; } } Load a customer with their orders: var customer = await db.Customers .Include(c => c.Orders) .FirstOrDefaultAsync(c => c.Id == id, ct); Multiple levels with ThenInclude: var orders = await db.Orders .Include(o => o.Customer) .Include(o => o.Items) .ThenInclude(i => i.Product) .Where(o => o.CreatedAt >= from) .ToListAsync(ct); Filtered include (EF Core 5+): var customers = await db.Customers .Include(c => c.Orders.Where(o => o.Total > 1000).OrderByDescending(o => o.CreatedAt).Take(5)) .ToListAsync(ct); Why use it - Avoids the N+1 problem, where loading 100 orders and then touching order.Customer for each would cause 100 extra queries (with lazy loading). Things to watch - Cartesian explosion: including several collections in one query multiplies rows (a customer with 50 orders and 20 addresses returns 1,000 rows). Use AsSplitQuery() to load each collection with a separate SQL query. - Over-fetching: Include loads full entities with all columns. For API responses, a projection is often better: var dtos = await db.Orders.Select(o => new OrderDto(o.Id, o.Customer.Name, o.Items.Count)).ToListAsync(ct); Projections do not need Include at all — EF generates the necessary joins automatically. - Combine with AsNoTracking() for read-only queries. - Avoid including large or unbounded collections in list endpoints. Other loading strategies for comparison: explicit loading (db.Entry(order).Collection(o => o.Items).LoadAsync()) and lazy loading proxies (convenient but risky for performance in web apps).

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics