I’m trying to insert a selectList into a view (a form). I figured I would do it by populating the list in the controller and sending it to the view as a viewbag. Here’s what I got so far:
var query = from p in db.ProductCategories
join pt in db.ProductCategoriesTranslations on p.ProductCategoriesId equals pt.ProductCategoriesId
where pt.ProductLanguage.Equals("se")
orderby pt.ProductCategoriesName
select new SelectListItem
{
Value = p.ProductCategoriesId.ToString(),
Text = pt.ProductCategoriesName
};
ViewBag.ProductCategoriesId = query;
return View();
Then in the view I have:
@Html.DropDownList("ProductCategoriesId", String.Empty)
I thought this was simple and straightforward but when I load the thing it crashes with the following error:
LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression.
Any suggestions?
Linq to SQL cannot translate
ToString()to any SQL command. That’s understandable. You should execute your query before you convert them toSelectListItems(or avoid the ToString() call). E.g.Please note that Linq2Sql evaluates the expression when you call
query.ToList(). Until this point there is no SQL running.The other problem is described in Leniel Macaferi’s answer.
Update
Becase the target technology changed (question tag) since my answer I can suggest you a different approach too:
You can use SqlFunctions.StringConvert instead of
ToStringin your LINQ query and EF can translate that.