How to Use LINQ with Entity Framework in C#
Use
LINQ queries on your DbSet properties in Entity Framework to retrieve data from the database in a readable way. You write queries using from, where, select or method syntax like .Where() and .Select(), and Entity Framework translates them into SQL automatically.Syntax
LINQ queries with Entity Framework use either query syntax or method syntax on DbSet collections. The DbSet represents a table in your database.
- Query syntax: Uses keywords like
from,where,select. - Method syntax: Uses extension methods like
Where(),Select(),OrderBy().
Entity Framework converts these LINQ queries into SQL commands behind the scenes.
csharp
using(var context = new MyDbContext()) { // Query syntax var query1 = from c in context.Customers where c.City == "London" select c; // Method syntax var query2 = context.Customers .Where(c => c.City == "London") .Select(c => c); }
Example
This example shows how to use LINQ with Entity Framework to get customers from a specific city and print their names.
csharp
using System; using System.Linq; using Microsoft.EntityFrameworkCore; public class Customer { public int Id { get; set; } public string Name { get; set; } public string City { get; set; } } public class MyDbContext : DbContext { public DbSet<Customer> Customers { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder options) => options.UseInMemoryDatabase("TestDb"); } class Program { static void Main() { using var context = new MyDbContext(); // Add sample data context.Customers.Add(new Customer { Name = "Alice", City = "London" }); context.Customers.Add(new Customer { Name = "Bob", City = "Paris" }); context.Customers.Add(new Customer { Name = "Charlie", City = "London" }); context.SaveChanges(); // LINQ query to get customers from London var londonCustomers = context.Customers .Where(c => c.City == "London") .ToList(); foreach (var customer in londonCustomers) { Console.WriteLine(customer.Name); } } }
Output
Alice
Charlie
Common Pitfalls
Common mistakes when using LINQ with Entity Framework include:
- Forgetting to call
ToList()orToArray()to execute the query and get results. - Using unsupported methods or .NET functions inside LINQ queries that cannot be translated to SQL.
- Not disposing the
DbContextproperly, leading to connection leaks. - Modifying data inside a LINQ query instead of after fetching results.
csharp
/* Wrong: Using a method not supported by EF in query */ var result = context.Customers.Where(c => SomeLocalMethod(c.Name)).ToList(); /* Right: Fetch data first, then filter locally */ var allCustomers = context.Customers.ToList(); var filtered = allCustomers.Where(c => SomeLocalMethod(c.Name));
Quick Reference
Tips for using LINQ with Entity Framework:
- Use
DbSetproperties to start queries. - Prefer method syntax for chaining multiple operations.
- Call
ToList()orToArray()to execute queries and get results. - Use
asyncmethods likeToListAsync()for better performance in real apps. - Keep queries simple to ensure they translate well to SQL.
Key Takeaways
Use LINQ queries on DbSet properties to retrieve data with Entity Framework.
Entity Framework translates LINQ into SQL automatically for database operations.
Always execute queries with ToList() or ToArray() to get results.
Avoid using unsupported .NET methods inside LINQ queries to prevent errors.
Dispose DbContext properly to manage database connections.