问题描述
我有一个类Main
,它具有各种类型的ICollection
(SubA
和SubB
,父类是Parent
).我需要编写一个LINQ查询,该查询使用每个表层次结构基于EF中的这些子类型进行过滤. TPH不允许直接查询Type
列,因此我试图找出一种解决方法.我在Parent
上有一个方法来获取类型字符串. LINQ不支持此功能.
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.
如何从Main
执行LINQ查询以筛选每个子类型(SubA
和SubB
)以及该子项的另一个属性?
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;
}
这是我正在尝试的LINQ查询,但由于LINQ不支持ReturnType()
而失败.
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);
推荐答案
您可以执行以下操作:
query = query.Where(m => m.StatusId != 4 && (m is SubA || m is SubB));
或更复杂的使用OfType
:
var subQuery = query.Where(m => m.StatusId != 4);
query = subQuery.OfType<SubA>()
.Cast<Main>()
.Union(subQuery.OfType<SubB>().Cast<Main>());
这篇关于实体框架-使用TPH按ICollection类型过滤LINQ的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!