Apparently, according to this you cannot query a many relationship without loading the entire collection. In other words, it’s a LINQ to Objects instead of a LINQ to Entities query.
E.g.
Category category = db.Categories.Find(1);
var productsThatStartWithA = category.Products.Where(p => p.Name.StartsWith("A")).ToList();
The above query loads all products in that category, and the filter is applied afterwards.
Question #1
Is this correct? I can’t believe how stupid this is.
Question #2
Does LINQ to SQL or any other LINQ enabled ORM handle this the way it’s supposed to work?
The alternatives presented in the linked question and in Slauma’s answer are workarounds, not solutions. They require a reference to the context object, which is not available if you write code that is decoupled from the Entity Framework API, and/or your code is object-oriented, e.g.:
public class Category {
public IEnumerable<Product> GetProductsThatStartWithA() {
return this.Products.Where(p => p.Name.StartsWith("A")).ToList()
}
}
The sad is that Linq to SQL actually provide much better support for this (with
DataLoadOptions.AssociateWithbut it is still not exactly what you want) whereas Linq to entities / EF provides only what you call workaround – even with respect to the implementation and existing difference betweenIEnumerableandIQueryableit looks like correct solution.What you want will require collection to expose
IQueryableand internally call the code showed by @Slauma if collection is not loaded = linq-to-entities or common linq-to-objects on loaded collection. I’m not sure if it can work but you can play with it. Here you have some starting points:Btw. you must turn off EF’s lazy loading otherwise it will take precedence.