I need to get the number of products. I have two entities, the first SubCatgory and the second is Product. So I have two ways to get product count. the first:
var subcatgory = await _context.SubCategories.FirstOrDefaultAsync(m => m.Id == id);
int productCount = await _context.Products.CountAsync(p => p.SubCatgoryId == id);
the second:
var subcatgory = await _context.SubCategories.Include(s => s.Products).FirstOrDefaultAsync(m => m.Id == id);
int productCount = subcatgory.Products.Count();
Which one is better in terms of performance? Why? tip: I need subcatgory too.
Thank you for your answer
CodePudding user response:
Try the following query. It returns data in one roundtrip to database.
var result = await _context.SubCategories
.Where(m => m.Id == id)
.Select(sc => new
{
Subcategory = sc,
ProductCount = sc.Products.Count()
})
.FirstOrDefaultAsync();