Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq UNION query to select two elements

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

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.

like image 897
Leron_says_get_back_Monica Avatar asked Feb 22 '13 10:02

Leron_says_get_back_Monica


1 Answers

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

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

like image 166
Tom Avatar answered Nov 07 '22 03:11

Tom