Reputation: 7864
I'm have a class, Main
, that has an ICollection
of various types (SubA
and SubB
, parent class is Parent
). I need to write a LINQ query that filters based on these subtypes in EF using table-per-hierarchy. TPH doesn't allow querying the Type
column directly, so I'm trying to figure out a workaround. I have a method on Parent
to get the type string. LINQ doesn't support this, however.
How can I perform a LINQ query from Main
to filter on the type of each child (SubA
and SubB
), as well as one additional property of the child?
This is the class method to get the type:
public virtual string ReturnType()
{
return GetType().BaseType.Name;
}
This is the LINQ query I was attempting, but fails because ReturnType()
isn't supported in LINQ.
// Main query defined elsewhere in function
query = query.Where(main => main.children.All(child =>
(child.ReturnType() == "MS" || child.ReturnType() == "TL") &&
child.StatusId != 4);
Upvotes: 0
Views: 673
Reputation: 4773
You can do something like this:
query = query.Where(m => m.StatusId != 4 && (m is SubA || m is SubB));
Or trickier with OfType
:
var subQuery = query.Where(m => m.StatusId != 4);
query = subQuery.OfType<SubA>()
.Cast<Main>()
.Union(subQuery.OfType<SubB>().Cast<Main>());
Upvotes: 3