在 Linq 中将 int 转换为字符串到实体的问题 [英] Problem with converting int to string in Linq to entities

查看:31
本文介绍了在 Linq 中将 int 转换为字符串到实体的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var items = from c in contacts
            select new ListItem
            {
                Value = c.ContactId, //Cannot implicitly convert type 'int' (ContactId) to 'string' (Value).
                Text = c.Name
            };
var items = from c in contacts
            select new ListItem
            {
                Value = c.ContactId.ToString(), //Throws exception: ToString is not supported in linq to entities.
                Text = c.Name
            };

无论如何我可以做到这一点吗?请注意,在 VB.NET 中使用第一个代码段没有问题,它工作得很好,VB 很灵活,我无法习惯 C# 的严格性!!!

Is there anyway I can achieve this? Note, that in VB.NET there is no problem use the first snippet it works just great, VB is flexible, im unable to get used to C#'s strictness!!!

推荐答案

使用 EF v4,您可以使用 SqlFunctions.StringConvert.int 没有重载,因此您需要转换为双精度或小数.你的代码最终看起来像这样:

With EF v4 you can use SqlFunctions.StringConvert. There is no overload for int so you need to cast to a double or a decimal. Your code ends up looking like this:

var items = from c in contacts
            select new ListItem
            {
                Value = SqlFunctions.StringConvert((double)c.ContactId).Trim(),
                Text = c.Name
            };

这篇关于在 Linq 中将 int 转换为字符串到实体的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆