Advertisement
Advanced C#, LINQ

How does LINQ to Objects differ fundamentally from LINQ to Entities (Entity Framework), particularly regarding how the query is actually executed?

Short answer

LINQ to Objects compiles queries into regular, DIRECTLY-EXECUTABLE C# delegates that run in-process against in-memory collections; LINQ to Entities (via IQueryable ) instead builds an EXPRESSION TREE representing the query's structure, which Entity Framework TRANSLATES into SQL…

Save C# mock interview
Advertisement
AModel answer
LINQ to Objects compiles queries into regular, DIRECTLY-EXECUTABLE C# delegates that run in-process against in-memory collections; LINQ to Entities (via IQueryable<T>) instead builds an EXPRESSION TREE representing the query's structure, which Entity Framework TRANSLATES into SQL and executes on the DATABASE SERVER — meaning not every C# expression/method is translatable, and some LINQ code that works fine against a List<T> throws at runtime against a DbSet<T>.
IEnumerable<User> inMemory = users.Where(u => u.IsActive); // runs entirely in C#, in-process

IQueryable<User> fromDb = dbContext.Users.Where(u => u.IsActive); // translated to SQL: WHERE IsActive = 1
// dbContext.Users.Where(u => SomeComplexCSharpOnlyMethod(u)); // may throw: can't translate to SQL
Real-world example
Debugging a runtime error where a LINQ query worked fine in a unit test against an in-memory List<T> but failed against the real Entity Framework DbSet<T>.
Likely follow-ups
  • Why does calling .ToList() or .AsEnumerable() partway through an EF Core query change what CAN be used in the REMAINING LINQ chain?
Related topics