C# Linq UNION 查询选择两个元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15022405/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Linq UNION query to select two elements
提问by Leron_says_get_back_Monica
I want to select 2 elements from my database table using LINQ
query and I saw an example which use UNION
I don't have much experience but I think that maybe this is what I need but I get an error which I can not fix and I'm not sure if it's fixable anyway. So here is my query:
我想使用LINQ
查询从我的数据库表中选择 2 个元素,我看到了一个使用UNION
我没有太多经验的例子,但我认为这可能是我需要的,但我得到一个我无法修复的错误,我是不确定它是否可以修复。所以这是我的查询:
IList<String> 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();
Which as it seems is complaining about trying to use UNION
on IQueryable
with IEnumarebale
. I tried to fix that by adding ToString()
like this - (tom.ID).ToString
which led to cleaning the error underline in Visual-Studio-2010
but in runtime I get:
其中,因为它似乎在抱怨试图使用UNION
上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.
泰,勒伦。
采纳答案by Tom
EDIT:
编辑:
Ok I found why the int.ToString() in LINQtoEF fails, please read this post: Problem with converting int to string in Linq to entities
好的,我找到了 LINQtoEF 中的 int.ToString() 失败的原因,请阅读这篇文章: 在 Linq 到实体中将 int 转换为字符串的问题
This works on my side :
这对我有用:
List<string> materialTypes = (from u in result.Users
select u.LastName)
.Union(from u in result.Users
select SqlFunctions.StringConvert((double) u.UserId)).ToList();
On yours it should be like this:
在你的应该是这样的:
IList<String> 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();
Thanks, i've learnt something today :)
谢谢,我今天学到了一些东西:)