Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format a string in a linq expression?

Tags:

c#

linq

Given the following code

IQueryable<string> customers = 
    from Customers in db.Customers
    where Customers.CstCompanyName.Contains(prefixText) && Customers.CstInactive == false
    select Customers.CstCompanyName + " (Phone: " + Convert.ToInt64(Customers.CstPhone).ToString("###-###-#### ####") + ")";

This is a call to my entity framework. I am returning a phone number from the database. I am trying to format it in the given format string. Unfortunately, when I run this, I receive the following error:

LINQ to Entities does not recognize the method 'System.String ToString(System.String)' method, and this method cannot be translated into a store expression.

So my question is how do I return this database object as a formatted string?

Thanks!

like image 966
Kevin Avatar asked Mar 02 '12 14:03

Kevin


1 Answers

I would perform the querying in the database, but the formatting locally:

var customers = db.Customers
                  .Where(c => c.CstCompanyName.Contains(prefixText))
                  .Select(c => new { c.CstCompanyName, c.CstPhone })
                  .AsEnumerable() // Switch to in-process
                  .Select(c => c.CstCompanyName + 
                               " (Phone: " +            
                               Convert.ToInt64(Customers.CstPhone)
                                      .ToString("###-###-#### ####") + ")");
like image 109
Jon Skeet Avatar answered Oct 17 '22 01:10

Jon Skeet