簡體   English   中英

在ASP.NET MVC 5中可查詢到IEnumerable

[英]IQueryable to IEnumerable in ASP.NET MVC 5

這是我的代碼:

控制器:

    public async Task<ActionResult> Index()
    {
        if(User.IsInRole("admin")){
            return View(await db.Customers.ToListAsync());
        }
        else if(User.IsInRole("employee"))
        {
            var list = from c in db.Customers
                       where c.User.Id == User.Identity.GetUserId()
                       select c;
            var e = list.AsEnumerable();                
            return View(e);


            //tried this too : 
            //var list = db.Customers.Where(c=>c.User == User); 
            //return View(list);

        }
        return RedirectToAction("Error");
    }

查看:

@model IEnumerable<AspnetIdentitySample.Models.ApplicationUser>

<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.UserName)
        </th>
    </tr>

    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.UserName)

            </td>

        </tr>
    }

</table>

為什么我不能在視圖中顯示查詢結果? 任何幫助,將不勝感激! :) 謝謝。

這是由於所謂的延遲執行 您正在返回一個IQueryable實例..但是該實例不保存所需的數據。 它包含一個執行計划,可用於查詢結果。

您需要強制評估查詢。 這樣做的一般方法是調用ToList() (注意,您已經在if語句的其他邏輯分支上完成了此操作):

return View(list.ToList());

您的問題(以及它們全部編譯的原因)是因為IQueryable實現IEnumerable 因此,將其傳遞給您的視圖很好。 IList還實現IEnumerable ..,因此ToList()強制對IQueryable評估,並且仍可以傳遞給視圖。

視圖中(在foreach循環之外)也存在此問題:

@Html.DisplayNameFor(model => model.UserName)

您的模型是一個集合..所以這將無法工作,因為IEnumerable<T>沒有UserName屬性(但它的項目具有)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM