如何将 and 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
编辑
我得到的错误是:
LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression
对于 EF v4,您可以使用 SqlFunctions.StringConvert。所以你的代码最终会是这样的:
from s in ctx.Services
where SqlFunctions.StringConvert((double)s.Code).StartsWith("1")
select s
编辑
正如里克在他的评论中提到的那样,将 int 转换为双精度数(小数可能也适用)的原因是该函数没有 int 的重载。
Linq to Entities 不支持将函数转换为服务器托管的 sql。
ToString(在任何东西上)就是其中之一
这是支持的功能列表
之前在 Stack overflow 上专门问过这个问题询问如何将 int 转换为字符串
我有类似的问题
IQueryable<Street> query = db.Streets.AsQueryable();
query = query.Where(street => street.Name.ToLower().StartsWith(keyword))
.Take(10)
.OrderBy(street => street.Name);
var list = query.Select(street => new
{
street.StreetId,
Name = street.Name + " " + street.Suburb.Name + " " + street.Suburb.State.Name + " " + street.Suburb.Postcode
});
street.Suburb.Postcode 将“无法转换非原始类型错误”作为其整数抛出?在跟随 shuggy 的链接后,我通过添加 .AsEnumerable 来强制 int 来修复? -> 字符串转换“客户端”,即 LINQ to Objects。即
var list = query.AsEnumerable().Select(street => new
{
street.StreetId,
Name = street.Name + " " + street.Suburb.Name + " " + street.Suburb.State.Name + " " + street.Suburb.Postcode
});
使用 LINQ to Objects 时,您可以使用 ToString() 帮助程序。
将 IQueryable 转换为 IEnumerable,因为 IQueryable 继承了 IEnumerable。请参阅http://msdn.microsoft.com/en-us/library/system.linq.iqueryable.aspx - 特别是:“枚举导致与 IQueryable 对象关联的表达式树被执行。”我认为重要的是““执行表达式树”的定义特定于查询提供者”。
IQueryable 非常强大,但在这种情况下被误用了。
我试过这个解决方法,它对我有用:
from s in ctx.Services
where (s.Code + "").StartsWith("1")
select s
希望这有帮助
这是一种方法。
int[] x = new int[] {11,3,15,7,19};
var j = from s in x where s.ToString().StartsWith( "1") select s.ToString();
Console.WriteLine( j );
from s in ctx.Services.ToList()
where s.Code.ToString().StartsWith("1")
select s
var items = from c in contacts
select new ListItem
{
Value = String.Concat(c.ContactId), //This Works in Linq to Entities!
Text = c.Name
};
我发现 SqlFunctions.StringConvert((double)c.Age) 对我不起作用,或者该字段的类型为 Nullable
在过去几天的反复试验中,我进行了大量搜索才找到这个。
我希望这能帮助一些编码员。