Problem with converting int to string in Linq to entities(在 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 转换为字符串到实体的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Linq 中将 int 转换为字符串到实体的问题


基础教程推荐
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01