Cast linq results to List<MyInterface>

六月ゝ 毕业季﹏ 提交于 2019-12-18 15:33:20

问题


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:


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;



回答2:


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.




回答3:


return results.Count() > 0 ? 
results.Select(result => (IApplicationEntity)result)
.ToList() : null;


来源:https://stackoverflow.com/questions/1361085/cast-linq-results-to-listmyinterface

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!