简体   繁体   中英

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. 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 . Thanks!

Apparently, Entity Framework does not know (enough) about the relation between TypeA and TypeB. If you can define it as a navigation property , that would solve your problem.

If that is not possible, inserting .AsEnumerable() should work:

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). 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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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