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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 13:49:43  来源:igfitidea点击:

Linq UNION query to select two elements

c#visual-studio-2010linq

提问by Leron_says_get_back_Monica

I want to select 2 elements from my database table using LINQquery and I saw an example which use UNIONI 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 UNIONon IQueryablewith IEnumarebale. I tried to fix that by adding ToString()like this - (tom.ID).ToStringwhich led to cleaning the error underline in Visual-Studio-2010but in runtime I get:

其中,因为它似乎在抱怨试图使用UNIONIQueryableIEnumarebale。我试图通过这样添加来解决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 :)

谢谢,我今天学到了一些东西:)