In this article I will explain with an example, how to solve the following error (exception) when using LINQ to SQL or Lamba expressions on DbSet records returned by Entity Framework in C# .Net.
LINQ to Entities does not recognize the method System.String ToString() method, and this method cannot be translated into a store expression.
Exception
In following code snippet, a LINQ to SQL query is executed on the records returned from the Entity Framework.
CustomersEntities entities = new CustomersEntities();
List<SelectListItem> customerList = (from p in entities.Customers
select new SelectListItem
{
Text = p.Name,
Value = p.CustomerId.ToString()
}).ToList();
But it raises the following exception:-
LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression.
Reason
This exception occurs because LINQ to SQL query internally builds an SQL query and executes it on the database directly and hence when one tries to use the ToString method which is a .Net data type conversion method and cannot be used for an SQL Query.
Solutions
1. StringConvert method
The first solution to this problem is to use the StringConvert method of the SqlFunctions class for converting the Integer value to String.
First you will need to import the following namespace.
using System.Data.Objects.SqlClient;
And then use it in the LINQ to SQL query as follows.
CustomersEntities entities = new CustomersEntities();
List<SelectListItem> customerList = (from p in entities.Customers
select new SelectListItem
{
Text = p.Name,
Value = SqlFunctions.StringConvert((decimal)p.CustomerId)
}).ToList();
Note: StringConvert method accepts only Decimal and Double data types and hence you will need to first convert your variable to either decimal or double before using this function.
2. Convert to Enumerable
The next solution to this problem is to convert the Entity Framework DbSet to Enumerable List in the LINQ to SQL query as shown as follows.
The reason it will work the AsEnumerable function copies the records from DbSet to Enumerable List and thus now the .Net functions for conversion can be easily used.
CustomersEntities entities = new CustomersEntities();
List<SelectListItem> customerList = (from p in entities.Customers.AsEnumerable()
select new SelectListItem
{
Text = p.Name,
Value = p.CustomerId.ToString()
}).ToList();