返回 List<> 的 LINQ 查询作为班级成员
给定以下数据类,
public class EmployeeMenu
{
public int ID { get; set; }
public string HeaderName { get; set; }
public List<string> ItemNames { get; set; }
}
如何将子查询放入 ItemNames
字段中?
我当前的查询
IQueryable<EmployeeMenu> retValue =
from mh in menuHeaders
select new EmployeeMenu
{
ID = mh.ID,
HeaderName = mh.HeaderName,
ItemNames = (from mhi in mh.MenuItems
select mhi.MenuItemName).ToList<string>()
};
似乎没有成功......
数据结构是
MenuHeaders MenuItems
----------- ---------
ID ID
HeaderName <-(FK)--MenuHeaderID
MenuItemName
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我最终只是从 List 更改为 IEnumerable。这解决了它。
I ended up just changing from a List to IEnumerable. This fixed it.
您不想在子选择中放置一个 where 来过滤到 MenuHeaderID 等于 mh.HeaderName 的所有菜单项吗?如果您愿意,也可以将 .Equals() 与 StringComparison 类型一起使用。
这是一个例子...
Wouldnt you want to just put a where in your sub-select to filter that down to all the menu items with the MenuHeaderID equals mh.HeaderName. You can just .Equals() with the StringComparison type if you want as well.
Here is an example...
我的猜测是您没有在班级内初始化该列表。我的这一点基于我在 Nhibernate 上的经历。
希望这有帮助。
My guess is that your not initiliazing the list within your class. I basing this off the experience I was having with Nhibernate.
Hope this helps.
好的。 如果您想在某处使用 where 子句,请尝试替换
为
I Question,但这应该可以帮助您克服运行时异常。
每当您看到“LINQ to Entities 确实识别该方法...并且该方法无法转换为存储表达式”形式的错误消息时,LINQ to Entities 都会告诉您它无法弄清楚如何翻译部分将表达式树转换为 SQL 语句。这意味着您需要将内容拉到客户端,以便 LINQ to Entities 不会尝试翻译它无法翻译的内容。
Okay. Try replacing
by
I question if you want a where clause in there somewhere, but this should get you past the runtime exception.
Any time you see an error message of the form "LINQ to Entities does recognize the method ... and this method can not be translated into a store expression" LINQ to Entities is telling you that it can't figure out how to translate part of the expression tree into a SQL statement. This means you need to pull things client side so that LINQ to Entities doesn't try to translate something that it can't translate.