Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate int and string in LINQ to Entities

I am using the following code:

from c in Country
 where c.IsActive.Equals(true)
 orderby c.CountryName
 select new
 {
     countryIDCode = c.CountryID + "|" + c.TwoDigitCode,
     countryName = c.CountryName
 }

But I get this error while running it:

Unable to cast the type 'System.Int32' to type 'System.Object'. LINQ to Entities only supports casting Entity Data Model primitive types.

CountryID is int type and TwoDigitCode is string type.

How do I concatenate properly?

like image 724
Waheed Avatar asked Apr 21 '10 10:04

Waheed


2 Answers

This is a limitation of the old version of the Entity Framework. I think that with v4 it is solved. For your version the workaround is to convert the result to an enumerable:

from a in 
(from c in Country
where c.IsActive.Equals(true)
orderby c.CountryName).AsEnumerable()
select new
{
    countryIDCode = a.CountryID + "|" + a.TwoDigitCode,
    countryName = a.CountryName
}
like image 51
David Espart Avatar answered Oct 18 '22 20:10

David Espart


There is no mapping to a Canonical Function for the int to string casting.

So just return the Int and the String in 2 different columns and then concatenate them in .NET after using the AsEnumerable method:

var cListTemp = from c in Country
    where c.IsActive.Equals(true)
    orderby c.CountryName
    select new
    {
        countryID = c.CountryID,
        twoDigitCode = c.TwoDigitCode,
        countryName = c.CountryName
    };

var cList = cListTemp.AsEnumerable().Select(c => new {
    countryIDCode = c.countryID + "|" + c.twoDigitCode,
    countryName = c.countryName
});
like image 43
Mariano Desanze Avatar answered Oct 18 '22 21:10

Mariano Desanze