I’ve one kind of request that I often use in Linq:
I need a set of data, which have their ID(or any other field) which is in a list of items.
This is an heavy request because I’ve a lot of (used) Include to load data.
So an example:
I’ve a table with person, with this kind of structure:
Id; Name; Age; ...
This table as several tables linked with a foreign key, and I need to load those data:
Car, Company, Address, …
And now I want to retrieve all data of people having a special age:
List<int> ages = new List<int>(){7,17,27,37,47,57,67,77,87};
using (MyDatabaseEntities context = new MyDatabaseEntities ())
{
return context.Persons.Include("Car").Include("Company").Include("Address")
.Where(p=>ages.Contains(p.Age)).ToList();
}
The problem is that I’ve the impression that Linq doesn’t know that my “ages” list will not change, and then download the full list of Persons, with all their datas(Car, Company, …) and then checks every result if it has the correct age.
So.
- Am I right?
- How to avoid this?
You can use projection like this: