In LINQ to Entities, concatenate int and string.

entity-framework linq linq-to-entities

Question

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?

1
11
6/24/2015 9:25:14 PM

Accepted Answer

If this error is preventing you from progressing and is a small dataset you could could hydrate your retrieval from the database by by enumerating the query (call ToList). From that point on, your operations will be against in-memory objects and you may not encounter the error you are receiving.

var countries = (from c in Country
where c.IsActive.Equals(true)
orderby c.CountryName
select c).ToList();


var countryCodes = (from c in countries
where c.IsActive.Equals(true)
    orderby c.CountryName
    select new
    {
        countryIDCode = c.CountryID + "|" + c.TwoDigitCode,
        countryName = c.CountryName
    });
7
4/21/2010 12:06:50 PM

Popular Answer

Use System.Data.Objects.SqlClient.SqlFunctions.StringConvert

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


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow