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

This is my controller class

public class HomeController : Controller
{
    private rikuEntities rk = new rikuEntities();
    public ActionResult Index()
    {
        var db = new rikuEntities();
        IEnumerable<SelectListItem> items = db.emp.Select(c => new     
               SelectListItem
               {
                 Value = c.Id.ToString(), 
                 Text = c.name
               });
        ViewBag.CategoryID = items;
        return View();
    }
}

this is my look

@using (Html.BeginForm("viewToController", "Home"))
{
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>emp</legend>

        <div class="editor-field">
            @Html.DropDownList("CategoryID", (IEnumerable<SelectListItem>) ViewBag.Categories)
        </div>
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

whenever I run this program, I get this error:

LINQ to Entities does not recognize the 'System.String ToString ()' method, and this method cannot be translated into a storage expression. "in the expression @ Html.DropDownList (" CategoryID ", (IEnumerable) ViewBag.Categories) . I use the entity framework mechanism to connect to the database. Help me find out about the error ...

+3
source share
2 answers

ViewBag. , :

public class EmployeeViewModel
{
    public string CategoryId { get; set; }
    public IEnumerable<Employee> Categories { get; set; }
}

:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var db = new rikuEntities();
        var model = new EmployeeViewModel
        {
            Categories = db.emp.ToArray() // <-- you probably want categories here
        };
        return View(model);
    }
}

:

@model EmployeeViewModel
@using (Html.BeginForm("viewToController", "Home"))
{
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>emp</legend>

        <div class="editor-field">
            @Html.DropDownListFor(
                x => x.CategoryId,
                new SelectList(Model.Categories, "Id", "name")
            )
        </div>
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}
+4

EF , ToString() SQL.

SqlFunctions.StringConvert.

int, double: - (

var items = from v in db.emp  
   select new SelectListItem
   {     
       Text = c.name,        
       Code = SqlFunctions.StringConvert((double)c.Id)
   }; 
+3

All Articles