LINQ到实体只支持转换实体数据模型原语类型
本文关键字:实体 数据模型 原语 转换 类型 支持 LINQ | 更新日期: 2023-09-27 18:17:40
我想在我的视图中填充一个下拉列表。非常感谢任何帮助。谢谢。
错误:无法强制转换类型"System"。Int32' to type 'System.Object'.
LINQ to Entities只支持转换实体数据模型原语类型。
控制器:
ViewBag.category = (from c in new IntraEntities().CategoryItems
select new SelectListItem() {Text=c.Name, Value=""+c.ID }).ToList<SelectListItem>();
视图:
Category:<br />@Html.DropDownList("category", (List<SelectListItem>)ViewBag.category)
这个怎么样:
ViewBag.category =
from c in new IntraEntities().CategoryItems.ToList()
select new SelectListItem
{
Text = c.Name,
Value = c.ID.ToString()
};
和如何使用强类型的视图模型,而不是一些弱类型的废话ViewBag(这是我叫它的方式)?
:
public class CategoryViewModel
{
public string CategoryId { get; set; }
public IEnumerable<SelectListItem> Categories { get; set; }
}
:
public ActionResult Foo()
{
var model = new CategoryViewModel
{
Categories =
from c in new IntraEntities().CategoryItems.ToList()
select new SelectListItem
{
Text = c.Name,
Value = c.ID.ToString()
}
};
return View(model);
}
最后在强类型视图中:
@model CategoryViewModel
@using (Html.BeginForm())
{
@Html.DropDownListFor(x => x.CategoryId, Model.Categories)
<button type="submit">OK</button>
}
好多了,你不觉得吗? 您可以在转换之前将查询强制转换为.AsEnumerable(),以强制它使用Linq to Objects进行转换,但最好使用System.Data.Objects.SqlClient.SqlFunctions中可用的SQL兼容函数,如下所示:
(from c in new IntraEntities().CategoryItems
select new SelectListItem() {
Text = c.Name,
Value = SqlFunctions.StringConvert((double)c.ID).TrimStart()
})
ViewBag.category = (from c in new IntraEntities().CategoryItems
select new SelectListItem {Text=c.Name, Value=c.ID.ToString()})
.ToList<SelectListItem>();
错误提示,您正在尝试将字符串与整数值连接起来。这在linq查询中是不可能的。对于Convert int into string,可以使用
SqlFunctions.StringConvert((decimal?)intProperty)
您可以使用SQL函数进行如下转换:
ViewBag.category = (from c in new IntraEntities().CategoryItems
select new SelectListItem() {
Text=c.Name,
Value=SqlFunctions.StringConvert((double) c.ID) }).ToList<SelectListItem>();
,但不要忘记在文件的顶部包含这个命名空间:
使用System.Data.Objects.SqlClient;是你正在尝试"连接字符串与整数值。这在linq查询中是不可能的,正如Nalan M建议的那样。确保它是您试图获取的数据库中的列。对我来说就是这样。我指定错列了。我之所以调用这个类,显然是因为有人为那个属性创建了一个类。如果你在visual studio中工作,你可以检查数据库,看看你正在调用的是什么。这样您就可以回答这个问题:"我想要的列在数据库中的哪个位置?"