Grid with list count property column


In this demo we show how you can have a count property in the grid, while also being able to sort and group by that property.
For this to work you need to add a get only property to your Entity (Lunch in our case public int MealsCount => Meals.Count();), after this you can use the count property as any other property.
However if you're using EntityFramework you'll also need to set the OrderByFunc on the GridModelBuilder.
GridWithListCountColumn/Index.cshtml
@(Html.Awe().Grid("Grid1")
.Columns(
new Column { Bind = "Id", Width = 75, Groupable = false, Resizable = false },
new Column { Bind = "Person" },
new Column { Bind = "Food", ClientFormatFunc = "site.imgFood", MinWidth = 200 },
new Column { Bind = "MealsCount" },
new Column { Bind = "MealsCount", ClientFormat = ".(MealsStr)", Header = "Meals"},
new Column { Bind = "Location" })
.Url(Url.Action("GetItems"))
.Height(350)
.Reorderable()
.Resizable())
Demos/Grid/GridWithListCountColumnController.cs
public class GridWithListCountColumnController : Controller
{
public IActionResult Index()
{
return View();
}

public IActionResult GetItems(GridParams g)
{
var list = Db.Lunches.AsQueryable();

return Json(new GridModelBuilder<Lunch>(list, g)
{
KeyProp = o => o.Id,// needed for Entity Framework | nesting | tree | api
Map = o => new
{
o.Id,
o.Person,
o.Food,
o.FoodPic,
o.Location,
o.Price,
o.MealsCount,
MealsStr = string.Join(", ", o.Meals.Select(m => m.Name))
},
OrderByFunc = (lunches, rules) =>
{
lunches = Dlinq.OrderBy(lunches, rules, new Dictionary<string, LambdaExpression>
{
{ "MealsCount", ExprHelper.GetCountLambda<Lunch>(o => o.Meals) }
});

return lunches;
}
}.Build());

// setting OrderByFunc in this demo is actually unnecessary because we're not using Entity Framework
// and we have Lunch.MealCount property that returns the count,
// but EF won't be able to translate OrderBy MealCount into a sql query
}
}



Comments