Reputation: 1107
For the purpose of this questions, let's assume I have these two Entities defined in my model -
public class Person
{
public Guid Id
{
get;
set;
}
public string Name
{
get;
set;
}
}
public class Parent : Person
{
public IEnumerable<Person> Children
{
get;
set;
}
}
Let's also assume that I have a PersonRepository which loads all people from the database. Now some people in the database will be a Parent entity and therefore have Children defined.
My question is, when I load the list of people from the repository, is it possible to instruct Linq to Include() the Children should any of the people be a Parent entity?
Btw, lazy-loading will not work in this instance as the repositories are used within a service layer.
Thank you for any help.
James
Upvotes: 1
Views: 584
Reputation: 364349
Unfortunatelly the only directly possible way is:
myContext.Persons.OfType<Parent>.Include("Children")...
The problem with this approach is that it will only load Parents. So the possible solution can be complex Linq query which will have two parts connected by .Contcat or .Union. One part will query only Persons and second part will query only Parents with included Childrens. Edit: It will work only in memory (IEnumerable) not in db (IQueryable).
So the other way can be run Person query first and then execute second query only for parents returned in the first query.
Upvotes: 1