destructi6n destructi6n - 2 months ago 37
C# Question

String.Format or toString not allowed in linq

The code below is not liked and throw the following error.


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


I was able to do it previously before I change the cost of my shipping method from decimal? to decimal. I changed it to decimal, and it started throwing an error, and then I changed it back and now it still doesn't like this. What is being done incorrectly here. I am simply trying to make the text a concatenation of the name of a shipping method with a - and the cost as the text.

var ShippingMethods = db.ShippingMethods.Select(x => new SelectListItem()
{
Text = x.Name + " - " + String.Format("c", x.Cost),
Value = x.Cost.ToString()
}).ToList();

Answer

You have to use .AsEnumerable() and the reason you can find from here

 db.ShippingMethods.AsEnumerable().Select(x => new SelectListItem()
                    {
                        Text = x.Name + " - " + String.Format("c", x.Cost),
                        Value = x.Cost.ToString()
                    }).ToList();
Comments