无法比较“System.Linq.IQueryable”1'类型的元素。仅支持基本类型,枚举类型和实体类型

时间:2016-04-02 04:53:33

标签: c# entity-framework linq asp.net-mvc-4

我在控制器中有这个代码

[HttpGet]
public ActionResult Nabipour()
{
    string name = "Nabipour";
    var username = (from T in _db.tbl_teacher
                    where T.Page==name
                    select T.Username);
    ViewBag.Nabipour = from N in _db.tbl_Tpage
                        where N.Username.Equals(username)
                        select N;
    ViewBag.papers = from P in _db.tbl_Tpaper
                     where P.Username.Equals(username)
                     select P;

    return View();
}

这是我对此行动的看法:

@{
    ViewBag.Title = "Nabipour";
    Layout = "~/Views/Shared/_otherpage.cshtml";
}
....
<ul>
    @foreach (var paper in ViewBag.papers)
    {
        <li><a href="~/Content/Paper/@paper.PaperName"></a></li>
    }                 
</ul>
....

因为您看到我没有在我的选择代码中检查null,而我在select中使用.FirstOrDefault()尝试了此代码。错误

  

无法比较类型&System; .Linq.IQueryable 1的元素。仅支持原始类型,枚举类型和实体类型

@foreach (var paper in ViewBag.papers),请帮助我该怎么办?

1 个答案:

答案 0 :(得分:1)

[HttpGet]
public ActionResult Nabipour()
{
    string name = "Nabipour";
    var username = (from T in _db.tbl_teacher
                    where T.Page==name
                    select T.Username).FirstOrDefault();
    ViewBag.Nabipour = from N in _db.tbl_Tpage
                        where N.Username.Equals(username)
                        select N;
    ViewBag.papers = (from P in _db.tbl_Tpaper
                     where P.Username.Equals(username)
                     select P).ToList();

    return View();
}