Linq int to string

pistacchio picture pistacchio · Aug 4, 2009 · Viewed 57.1k times · Source

how do I cast and int into a string? None of the following do works:

from s in ctx.Services
    where s.Code.ToString().StartsWith("1")
    select s

from s in ctx.Services
    where Convert.ToString(s.Code).StartsWith("1")
    select s

from s in ctx.Services
    where ((string)s.Code).ToString().StartsWith("1")
    select s

EDIT

The error I get is:

LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression

Answer

Brian Cauthon picture Brian Cauthon · Jul 20, 2010

With EF v4 you can use SqlFunctions.StringConvert. So your code would end looking like this:

from s in ctx.Services
where SqlFunctions.StringConvert((double)s.Code).StartsWith("1")
select s

EDIT

As Rick mentions in his comment, the reason for casting the int to a double (decimal probably works too) is that the function does not have an overload for int.