Linq UNION查询选择两个元素
我想使用LINQ
查询从我的数据库表中选择2个元素,我看到一个使用UNION
的例子我没有太多经验,但我想也许这就是我需要的但是我得到了一个我无法解决的错误而且我不管怎样,我不确定它是否可以修复。 所以这是我的查询:
IList materialTypes = ((from tom in context.MaterialTypes where tom.IsActive == true select tom.Name) .Union(from tom in context.MaterialTypes where tom.IsActive == true select (tom.ID))).ToList();
这似乎是抱怨尝试在IEnumarebale
上使用IQueryable
上的IEnumarebale
。 我尝试通过添加像这样的ToString()
来修复它 – (tom.ID).ToString
导致在Visual-Studio-2010
清除错误下划线但在运行时我得到:
{"LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression."}
Ty,Leron。
编辑:
好吧我发现为什么LINQtoEF中的int.ToString()失败了,请阅读这篇文章: 将Linq中的int转换为实体的问题
这对我有用:
List materialTypes = (from u in result.Users select u.LastName) .Union(from u in result.Users select SqlFunctions.StringConvert((double) u.UserId)).ToList();
你的应该是这样的:
IList materialTypes = ((from tom in context.MaterialTypes where tom.IsActive == true select tom.Name) .Union(from tom in context.MaterialTypes where tom.IsActive == true select SqlFunctions.StringConvert((double)tom.ID))).ToList();
谢谢,我今天学到了一些东西:)