Igor Levashov
Igor Levashov

Reputation: 328

Include entity and count data from different table in asp.net entity

I have two tables:

Talbe 1 - Items

id |  item  | categoryId
________________________
1  |  item1 |      1 
2  |  item2 |      2
3  |  item3 |      2

Table 2 - Categories

categoryid |  categoryName
___________________________
1          |  iphones 
2          |  ipads 
3          |  ipods 

Talbe 1 is dynamic, i.e. users add items, and I have View and want to display a table that shows Category and Number of Items in category. I am using entity.

My models

Item

public int id { get; set }
public string item { get; set; }
public virtual Category Category { get; set; }

Category

public int id { get; set; }
public string categoryName { get; set; }
public virtual Icollection<Item> Items { get; set; }

So I a confused how to count data in Items and attach to categories. Thanks.

Upvotes: 1

Views: 1138

Answers (1)

Shyju
Shyju

Reputation: 218782

You can use LINQ Count method on your Items property when querying categories.

Create a view model for your view.

public class CategoryVm
{
  public int Id {set;get;}
  public string Name {set;get;}
  public int ItemCount {set;get;}
}

and in your GET action method, you can use LINQ to query the Category table and project the result to a collection of CategoryVm

public ActionResult Categories()
{
  var db = new YourDbContext();
  var categoryVmList = db.Categories.Select(x=> new CategoryVm { 
                                                    Id=x.Id, 
                                                    Name=x.Name,
                                                    ItemCount = x.Items.Count() }
                                           ).ToList();
  return View(categoryVmList);
}

Now in your view (Categories.cshtml) which is strongly typed to a list of CategoryVm, you can iterate through the list and display the property values as needed.

@model List<CategoryVm>
<h2>Categories</h2>
@foreach(var cat in Model)
{
  <div>
    <p>@cat.Name <span>@cat.ItemCount</span></p>
  </div>
}

Upvotes: 1

Related Questions