Linq UNION查询选择两个元素

Ler*_*ica 19 c# linq visual-studio-2010

我想使用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();
Run Code Online (Sandbox Code Playgroud)

其中,因为它似乎在抱怨试图使用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."}
Run Code Online (Sandbox Code Playgroud)

Ty,Leron.

Tom*_*Tom 39

编辑:

好吧我发现为什么LINQtoEF中的int.ToString()失败了,请阅读这篇文章: 将Linq中的int转换为实体的问题

这对我有用:

        List<string> materialTypes = (from u in result.Users
                                      select u.LastName)
                       .Union(from u in result.Users
                               select SqlFunctions.StringConvert((double) u.UserId)).ToList();
Run Code Online (Sandbox Code Playgroud)

你的应该是这样的:

    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();
Run Code Online (Sandbox Code Playgroud)

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