gpt4 book ai didi

c# - LINQ to Entities 仅支持转换实体数据模型基元类型?

转载 作者:可可西里 更新时间:2023-11-01 08:35:17 26 4
gpt4 key购买 nike

我正在尝试在我的 View 中填充下拉菜单。任何帮助是极大的赞赏。谢谢。

错误:

Unable to cast the type 'System.Int32' to type 'System.Object'.

LINQ to Entities only supports casting Entity Data Model primitive types.

Controller :

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

以及如何使用强类型 View 模型而不是 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);
}

最后在您的强类型 View 中:

@model CategoryViewModel
@using (Html.BeginForm())
{
@Html.DropDownListFor(x => x.CategoryId, Model.Categories)
<button type="submit">OK</button>
}

好多了,你不觉得吗?

关于c# - LINQ to Entities 仅支持转换实体数据模型基元类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8496429/

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