gpt4 book ai didi

asp.net - LINQ to Entities 无法识别方法 'System.String ToString()' 方法,并且该方法无法转换为存储表达式

转载 作者:行者123 更新时间:2023-12-02 13:39:34 24 4
gpt4 key购买 nike

这是我的 Controller 类

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();
}
}

这是我的观点

@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>
}

每当我运行这个程序时,我都会收到此错误:

LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression." in the statement @Html.DropDownList("CategoryID", (IEnumerable) ViewBag.Categories). i am using entity framework mechanism for databse connection. please help me to find out the error...

最佳答案

我建议您使用 View 模型和强类型 View 而不是 ViewBag。因此,从定义 View 模型开始:

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

然后在 Controller 中填充此 View 模型:

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);
}
}

在 View 中:

@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>
}

关于asp.net - LINQ to Entities 无法识别方法 'System.String ToString()' 方法,并且该方法无法转换为存储表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6327818/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com