Home > Backend Development > C++ > How to Convert Int to String in LINQ to Entities Queries?

How to Convert Int to String in LINQ to Entities Queries?

Linda Hamilton
Release: 2025-01-25 18:26:10
Original
752 people have browsed it

How to Convert Int to String in LINQ to Entities Queries?

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template