简体   繁体   English

无法使用IQueryable在LINQ中进行强制转换?

[英]Can't do cast in LINQ with IQueryable?

I'm wondering how to get the query below to work: 我想知道如何使以下查询正常工作:

IQueryable<TypeA> data  = ...;                  
data = data.OrderBy(x => ((TypeB)x.RelatedObject).Value);

The error I get is: 我得到的错误是:

The specified type member 'RelatedObject' is not supported in LINQ to Entities. LINQ to Entities不支持指定的类型成员'RelatedObject'。 Only initializers, entity members, and entity navigation properties are supported. 仅支持初始化程序,实体成员和实体导航属性。

I'm very new to C#, I think this is a compile problem because I know RelatedObject is of TypeB . 我是C#的新手,我认为这是一个编译问题,因为我知道RelatedObjectTypeB Thanks! 谢谢!

Apparently, Entity Framework does not know (enough) about the relation between TypeA and TypeB. 显然,实体框架不了解(足够)有关TypeA和TypeB之间的关系。 If you can define it as a navigation property , that would solve your problem. 如果您可以将其定义为导航属性 ,那将解决您的问题。

If that is not possible, inserting .AsEnumerable() should work: 如果这不可能,则插入.AsEnumerable()应该可以:

data.AsEnumerable().OrderBy(x => ((TypeB)x.RelatedObject).Value);

What this will do, is having 'normal' LINQ performing the ordering, instead of the database (with an ORDER BY clause in the SQL query). 这将使“普通” LINQ而不是数据库(在SQL查询中带有ORDER BY子句)执行排序。 Note that it returns an IEnumerable<TypeA> instead of an IQueryable<TypeA> - depending on what you do with this variable, this might cause more records to be loaded into memory than strictly necessary. 请注意,它返回IEnumerable<TypeA>而不是IQueryable<TypeA> -根据对此变量的处理方式,这可能会导致将超出严格要求的记录加载到内存中。

If you know that you're only getting one specific type, you should be able to do something like this, assuming that EF knows about the inheritance. 如果您知道只得到一种特定类型,则假定EF知道继承,那么您应该可以执行类似的操作。

IQueryable<TypeA> data  = ...;                  
data = data.OfType<TypeB>().OrderBy(x => (x.RelatedObject).Value);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM