Linq int to string

pis*_*hio 48 .net linq linq-to-entities

如何将int和int转换为字符串?以下都不起作用:

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
Run Code Online (Sandbox Code Playgroud)

编辑

我得到的错误是:

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

Bri*_*hon 55

使用EF v4,您可以使用SqlFunctions.StringConvert.所以你的代码看起来像这样:

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

编辑

正如Rick在他的评论中提到的,将int转换为double(十进制可能也有效)的原因是该函数没有int的重载.

  • 这对我有用!唯一有趣的是,显然这个函数没有超载'int'.这就是为什么Brian在调用上面的函数之前将它作为双重拳击.在我看来,这需要标记为这个问题的答案. (10认同)
  • +1,但我想补充一点,我发现我必须在.StartsWith()之前使用.Trim()因为EF用空格填充数字. (6认同)
  • 这个答案现在比我的更有用,如果操作想要改变接受的答案就好了,否则我会添加一个注释来指示,从v4你应该使用你的答案. (2认同)

Shu*_*oUk 33

Linq to Entities不支持尽可能多的函数转换为服务器托管的sql.

ToString(在任何东西上)就是其中之一

这是支持的功能列表

之前已经在Stack溢出时询问过这一点,特别是询问如何将int转换为字符串

  • 你的第一个链接已经死了. (8认同)