我有一个具有“按表分层结构”继承的LINQ to实体模型。我对基本类型有一个查询,我想做特定于类型的逻辑。例如:
IQueryable<BaseType> base = ...
// this works fine
var result = base.Select(b => b is DerivedType1 ? 1 : 2).ToList();
// this doesn't compile to SQL
var result2 = base.Select(b => b is DerivedType1 ? ((DerivedType1)b).DerivedProperty : null).ToList();
有什么方法可以做这样的事情而无需分别处理每个派生类型的IQueryable:
// I'd rather not do this:
var resultA = base.OfType<DerivedType1>().Select(d => d.DerivedProperty);
var resultB = base.OfType<DerivedType2>().Select(d => default(int?));
var result = resultA.Concat(resultB).ToList();
最佳答案
LINQ-to-Entities不支持直接转换为像(DerivedType1)b
这样的实体类型,但是as
运算符(b as DerivedType1
)支持,因此您可以尝试:
var result2 = base
.Select(b => b is DerivedType1
? (b as DerivedType1).DerivedProperty
: null)
.ToList();
关于c# - 使用逐层继承表在LINQ to Entities查询中强制转换为派生类型,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12165805/