C# – LINQ to Entities does not recognize the method ‘System.String ToString()’ method MVC3

asp.net-mvc-3cvisual studio 2012

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

The error comes up while executing following code:

public ActionResult NewBooking()
    {
        var db = new VirtualTicketsDBEntities2();

        IEnumerable<SelectListItem> items = db.Attractions
          .Select(c => new SelectListItem
          {
              Value = c.A_ID.ToString(),
              Text = c.Name
          });
        ViewBag.CategoryID = items;
        return View();
    }

Any suggestion to get rid of this error?

Thanks.

Best Answer

You can use an AsEnumerable() to change the binding context from Linq-to-Entities to Linq-to-Objects:

IEnumerable<SelectListItem> items = db.Attractions
    .AsEnumerable()
    .Select(c => new SelectListItem
    {
        Value = c.A_ID.ToString(),
        Text = c.Name
    });
Related Topic