Linq UNION查询以选择两个元素 [英] Linq UNION query to select two elements

查看:105
本文介绍了Linq UNION查询以选择两个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用LINQ查询从数据库表中选择2个元素,我看到了一个使用UNION的示例,我经验不足,但是我认为这也许是我所需要的,但出现错误我无法修复,也不确定是否可以修复.所以这是我的查询:

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:

    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();

似乎在抱怨要在IQueryableIEnumarebale上同时使用UNION.我试图通过添加这样的ToString()-(tom.ID).ToString来解决此问题,这导致清除Visual-Studio-2010中的错误下划线,但是在运行时我得到了:

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:

{"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转换为字符串的问题到实体

Ok I found why the int.ToString() in LINQtoEF fails, please read this post: Problem with converting int to string in Linq to entities

这对我有效:

        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 :)

这篇关于Linq UNION查询以选择两个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆