ListMyInterface> with linq results

entity-framework linq linq-to-entities

Question

I have extended my entities to implement specific interfaces for its type. I am trying to perform the following query:

 var results = from x in context.MyEntityTable
               where x.AProperty == AValue
               select x;

 return results.Count() > 0 ? results.Cast<IApplicationEntity>().ToList() : null;

However, I keep getting the following error:

"LINQ to Entities only supports casting Entity Data Model primitive types"

Basically what I want to do is always convert the results from the raw entity type to a generic list of the interface it implements.

Is this possible?

1
9
9/1/2009 7:42:34 AM

Accepted Answer

You can do the cast on the client, bypassing the entity framework query translation layer by calling AsEnumerable extension method:

return results.Any()
       ? results.AsEnumerable().Cast<IApplicationEntity>().ToList() 
       : null;

However, it's better to reverse the order of doing the Count check:

var list = results.AsEnumerable().Cast<IApplicationEntity>().ToList();
return list.Count == 0 ? null : list;
21
7/5/2012 8:59:28 PM

Popular Answer

If you want to cast your results to a complex type, you need to force the code to use LINQ to Objects rather than LINQ to Entities.

Calling the AsEnumerable extension method before the cast is the trick here.

Try the following:

var results = from x in context.MyEntityTable
              where x.AProperty == AValue
              select x;

return results.AsEnumerable().Cast<IApplicationEntity>().ToList();

Also note that it's not wise to check Count() on the enumerable, since it means the collection is iterated over twice.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow