c# - 在 Linq to entities 中将 int 转换为字符串的问题

标签 c# asp.net linq-to-entities tostring

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# 的严格!!!

最佳答案

对于 EF v4,您可以使用 SqlFunctions.StringConvert . int 没有重载,因此您需要转换为 double 或 decimal。您的代码最终看起来像这样:

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

关于c# - 在 Linq to entities 中将 int 转换为字符串的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1066760/

相关文章:

c# - .NET 外部 dll 引用检查

c# - 我如何对这个简单的表单进行单元测试

c# - 当文件不存在时,File.Delete 不会抛出错误

c# - 当 url 末尾有 DOT (.) 时,Asp.Net MVC 路由操作方法不会调用

具有虚拟属性查询的 c# Entity Framework

c# - Entity Framework 是否支持 COUNT(*) OVER()

c# - Linq to Entities - 三层架构

c# - 创建和使用类名仅在运行时已知的类的实例

MySql.数据.MySqlClient.MySqlException : Incorrect datetime value

.net - ASP.net 的测试功能(对象测试台)