我正在尝试在MVC 3中的创建视图中填充组合框.这是我到目前为止所做的:
public ActionResult Create()
{
var db = new ErrorReportingSystemContext();
IEnumerable<SelectListItem> items = db.Locations
.Select(c => new SelectListItem
{
Value =c.id,
Text = c.location_name
});
ViewBag.locations = items;
return View();
}
Run Code Online (Sandbox Code Playgroud)
但是当我尝试运行它时会出现编译错误:
Cannot implicitly convert int to string
在这篇文章中,我读到了这样做
Value = SqlFunctions.StringConvert((double)c.ContactId)
Run Code Online (Sandbox Code Playgroud)
会解决问题然而当我尝试这样做时,我得到以下错误:
the name 'SqlFunctions' does not exist in the current context
我做错了什么?
更新:
做出Value = c.id.ToString()错误:
LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression.
您的问题是EF无法将转换转换为字符串或.ToString()方法.
所以你需要.AsEnumerable()在选择SelectListItems 之前评估数据库查询(通过调用)
IEnumerable<SelectListItem> items = db.Locations
.AsEnumerable()
.Select(c => new SelectListItem
{
Value = c.id.ToString(),
Text = c.location_name
});
Run Code Online (Sandbox Code Playgroud)
但是,这种方法存在一些性能问题,因为生成的SQL查询将如下所示:
SELECT * FROM Locations ...
Run Code Online (Sandbox Code Playgroud)
因此,如果Locations表有50列,EF将从所有列加载数据,尽管稍后您只需要来自两列的数据.
您可以告诉EF应该加载哪些列,首先选择一个匿名类型然后进入 SelectListItems:
IEnumerable<SelectListItem> items = db.Locations
.Select(c => new
{
c.id,
c.location_name
});
.AsEnumerable()
.Select(c => new SelectListItem
{
Value = c.id.ToString(),
Text = c.location_name
});
Run Code Online (Sandbox Code Playgroud)
生成的查询看起来像这样:
SELECT id, location_name FROM Locations
Run Code Online (Sandbox Code Playgroud)