简体   繁体   English

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

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

Here's my code : 这是我的代码:

CONTROLLER: 控制器:

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

VIEW : 查看:

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

Why can't I display the Query results to the view ? 为什么我不能在视图中显示查询结果? Any help would be appreciated! 任何帮助,将不胜感激! :) Thank you. :) 谢谢。

This is due to something called deferred execution . 这是由于所谓的延迟执行 You're returning an IQueryable instance.. but this instance doesn't hold the data you want. 您正在返回一个IQueryable实例..但是该实例不保存所需的数据。 It contains an execution plan with which to query for your results. 它包含一个执行计划,可用于查询结果。

You need to force evaluation of the query. 您需要强制评估查询。 The general way of doing this is calling ToList() (Notice that you've done this on your other logical branch for the if statement): 这样做的一般方法是调用ToList() (注意,您已经在if语句的其他逻辑分支上完成了此操作):

return View(list.ToList());

Your problem (and the reason it all compiles) is because IQueryable implements IEnumerable . 您的问题(以及它们全部编译的原因)是因为IQueryable实现IEnumerable So passing it to your view is fine. 因此,将其传递给您的视图很好。 IList also implements IEnumerable .. so ToList() forces evaluation of your IQueryable and can still be passed to the view. IList还实现IEnumerable ..,因此ToList()强制对IQueryable评估,并且仍可以传递给视图。

There is also this issue in the view (outside of the foreach loop): 视图中(在foreach循环之外)也存在此问题:

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

Your model is a collection.. so this won't work, since IEnumerable<T> doesn't have a UserName property (but its items do). 您的模型是一个集合..所以这将无法工作,因为IEnumerable<T>没有UserName属性(但它的项目具有)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM