Linq sorts a child in a query

I have an EF model as follows:

enter image description here

In this model, I can obviously use Categories.Products to get a list of products.

I have a query, as shown below, to return a list of categories, and Products as a list, which will be used in the ASP.NET MVC 3 view:

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

To show Products in the order of their SortOrder, I currently need to:

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

Insult line: @foreach (var product in category.Products.OrderBy(a => a.SortOrder)) as it handles a bit of my model in the view.

Is there a way to sort this in a query?

+8
c # linq asp.net-mvc-3 razor entity-framework
source share
1 answer

Is there a way to sort this in a query?

View models, of course:

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

and in the action of your controller you need to populate this view model:

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

and in the Index.cshtml you can get rid of ugly loops and use display templates:

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

and inside the display template for the category ( ~/Views/Shared/CategoryViewModel.cshtml )

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

and inside the display template for the product ( ~/Views/Shared/ProductViewModel.cshtml )

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

As an additional enhancement to the action of the controller, you can use AutoMapper to map between your domain models (EF objects) and your view models, which should be passed to the view.

+8
source share

All Articles