Convert integer to string in LINQ to Entities query: troubleshooting and solution
You may encounter errors when trying to convert an integer to a string in a LINQ to Entities query. This problem is mainly because implicit type conversion is not supported.
In the first code snippet:
<code class="language-csharp">var items = from c in contacts select new ListItem { Value = c.ContactId, //无法将类型“int”(ContactId)隐式转换为类型“string”(Value)。 Text = c.Name };</code>
The compiler will issue an error because it cannot implicitly convert the integer ContactId to the string Value.
Explicit conversion of an integer to a string using ToString() in LINQ to Entities also fails:
<code class="language-csharp">var items = from c in contacts select new ListItem { Value = c.ContactId.ToString(), //抛出异常:ToString 在 linq to entities 中不受支持。 Text = c.Name };</code>
Solution:
To solve this problem, you can use the SqlFunctions.StringConvert function in EF v4. However, since there is no overload for integer, you can convert it to a double precision float or decimal first:
<code class="language-csharp">var items = from c in contacts select new ListItem { Value = SqlFunctions.StringConvert((double)c.ContactId).Trim(), Text = c.Name };</code>
This method successfully converts the integer ContactId to a string and allows you to proceed with the LINQ to Entities query.
The above is the detailed content of How to Convert Int to String in LINQ to Entities Queries?. For more information, please follow other related articles on the PHP Chinese website!