这是我的控制器类
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无法识别方法'System.String ToString()'方法,并且此方法无法转换为商店表达式。“在声明 @ Html.DropDownList(”CategoryID“,(IEnumerable) )ViewBag.Categories)。我正在使用实体框架机制进行数据库连接。请帮我找出错误......
答案 0 :(得分:4)
我建议您使用视图模型和强类型视图而不是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>
}
答案 1 :(得分:3)
可悲的是,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)
};