I have a db model with the following tables:
A * ---- 1 B 1 ---- * C
Based on this schema I have created a Entity Data Model which allows me to load all the As in my DB. As I also use the Bs in my Linq queries I load the As like this:
using(MyEntities entities = new MyEntities()){
var result = from a in entities.As.Include("B") where a.Code == 123 && a.B.Code == 321 select a;
}
The results can be further filtered by the user so I am building filters depending on the user's selection like this:
int filterValue = 222; //FilterValue is passed in by the user
IList<Func<A, bool>> filters = new List<Func<A, bool>>();
filters.Add(x => x.B.C.Any(i => i.C.Code == filterValue));
...build more filters...
Later on I apply the filters using:
foreach (var filter in filters)
{
results = results.Where(filter);
}
Notice that in the filter code I'm using C reference (which is a collection of Cs开发者_运维问答). That's where EF fails because the C collection is empty (has not be loaded). How can I force EF to eagerly load all related properties for an object graph so I can apply my filters or is there a better way of doing this?
Thanks.
The reason why your C is not loaded is because you are not including it in your query. You must use:
entities.As.Include("B.C")
But the result is as described by @Eranga - you are transferring all records to your application and filters them in your application memory by linq-to-objects instead of doing filtering by linq-to-entities and transferring only filtered records.
You are using IList<Func<A, bool>>
as filters. This makes it a LINQ-to-Objects query. Thats why you are complaining C
collection is empty.
So instead use IList<Expression<Func<A, bool>>>
as filters.
精彩评论