c# - Linq 对查询中的子项进行排序

标签 c# linq entity-framework asp.net-mvc-3 razor

我有一个 EF 模型如下:

enter image description here

在这个模型上,我显然可以使用 Categories.Products接收产品列表。

我有如下查询以返回类别列表,其中产品作为要在 ASP.NET MVC 3 View 中使用的列表:

var categories = (from a in context.Categories.Include("Products")
                  orderby a.SortOrder ascending
                  select a).ToList();
return View(categories);

为了按 SortOrder 的顺序显示产品,我目前必须这样做:

<ul>
@foreach (var category in Model)
{
    <li>@category.Title
        <ul>
        @foreach (var product in category.Products.OrderBy(a => a.SortOrder))
        {
            <li>@product.Description</li>
        }
        </ul>
    </li>
}
</ul>

违规行是:@foreach (var product in category.Products.OrderBy(a => a.SortOrder))因为这是在 View 中处理我的一些模型。

有没有办法在查询中对此进行排序?

最佳答案

Is there a way to sort this in the query?

当然是查看模型:

public class CategoryViewModel
{
    public string Title { get; set; }
    public IEnumerable<ProductViewModel> Products { get; set; }
}

public class ProductViewModel
{
    public string Description { get; set; }
}

并在您的 Controller 操作中执行必要的操作来填充此 View 模型:

public ActionResult Index()
{
    var categories = 
        (from category in context.Categories
         orderby category.SortOrder ascending
         select new CategoryViewModel
         {
             Title = category.Title,
             Products = category
                 .Products
                 .OrderBy(p => p.SortOrder)
                 .Select(p => new ProductViewModel
                 {
                     Description = p.Description
                 })
             }).ToList(); 
        ).ToList();
    return View(categories);
}

并且在 Index.cshtml View 中,您可以摆脱丑陋的循环并使用显示模板:

@model IEnumerable<CategoryViewModel>
<ul>
    @Html.DisplayForModel()
</ul>

并在类别的显示模板内 (~/Views/Shared/CategoryViewModel.cshtml)

@model CategoryViewModel
<li>
    @Html.DisplayFor(x => x.Title)
    <ul>
        @Html.DisplayFor(x => x.Products)
    </ul>
</li>

在产品的显示模板中(~/Views/Shared/ProductViewModel.cshtml)

@model ProductViewModel
<li>
    @Html.DisplayFor(x => x.Description)
</li>

作为对 Controller 操作的进一步改进,您可以使用 AutoMapper在域模型(EF 对象)和应传递给 View 的 View 模型之间进行映射。

关于c# - Linq 对查询中的子项进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6448770/

相关文章:

c#代码转成QT C++

c# - 从 asmx 服务返回多行

entity-framework - 重新设计 EF 嵌套连接以避免 Azure 上的 MSDTC

entity-framework - 更新数据库时 Entity Framework 4.3 迁移异常

c# - 在有显式迁移挂起时添加迁移

c# - 是否建议使用 ECB 密码模式?

c# 应用程序持有文件,即使我已经完成了它的工作

c# - 比较两个连续的行 - 分组依据

c# - 使用 LINQ 订购两个不同的 C# 列表

c# - 从 lambda 表达式生成 sql server 查询的替代方法