加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – LINQ to Entities只支持转换Entity Data Model的原始类型

发布时间:2020-12-15 06:55:37 所属栏目:百科 来源:网络整理
导读:我想在我的看法中填充一个下拉列表.任何帮助是极大的赞赏.谢谢. 错误: Unable to cast the type ‘System.Int32’ to type ‘System.Object’. LINQ to Entities only supports casting Entity Data Model primitive types. 控制器: ViewBag.category = (f
我想在我的看法中填充一个下拉列表.任何帮助是极大的赞赏.谢谢.

错误:

Unable to cast the type ‘System.Int32’ to type ‘System.Object’.

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

控制器:

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

好多了,你不觉得吗

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读