Home > database >  having count of records in one to many navigation property
having count of records in one to many navigation property

Time:11-02

I have 4 tables 1-Cart 2-CartItems 3-CartItemDetails table 1 and 2 are one to many , table 2 and 3 are one two many

I want to retrieve have some data from Table 1 and 2 and just count of the CartItemDetails

public class CartDto
{
    public long CartId { get; set; }       
    public int FinalPrice { get; set; }
    public int CartItemDetailCount { get; set; }
    public List<CartItemDto> CartItems { get; set; }
}

  public class CartItemDto
{
    public long Id { get; set; }        
    public long PackageId { get; set; }
    public string PackageTitle { get; set; }     
}

so I did this

   var cart = await _context.School_Carts                    
                 .Include(p => p.CartItems)
                 .ThenInclude(p => p.CartItemDetails)
                .Where(p => p.BrowserId == BrowserId)
                .FirstOrDefaultAsync();

     var result = new CartDto()
            {
                FinalPrice = cart.FinalPrice ,
                CartId = cart.Id,
                CartItemDetailCount = cart.CartItems.Select(p=>p.CartItemDetails.Count()),
                CartItems = cart.CartItems.Select(p => new CartItemDto
                {                       
                    PackageTitle = p.Package.Title,
                    Id = p.Id,
                    PackageId = p.PackageId,
                    
                }).ToList(),
            };

how can I have the count in this situation?

CodePudding user response:

Believe that you need to flatten the CartItemDetails list to get all item via .SelectMany.

CartItemDetailCount = cart.CartItems.SelectMany(x => x.CartItemDetails).Count()

Demo @ .NET Fiddle

  • Related