Linq 集团相关实体

Linq Group by relative entites

我的方案:用户将能够创建列表并向这些列表中添加项目。我想做的是最多在用户创建的列表中找到项目。

项目实体

public  class Item:BaseEntity
{
    public string Name { get; set; }
    public decimal Price { get; set; }
    public decimal DiscountedPrice{ get; set; }
    public virtual ICollection<ItemList> ItemLists { get; set; }
}

项目列表实体

public class ItemList:BaseEntity
{
    public string Name { get; set; }
    public string Description { get; set; }
    public int UserId { get; set; }
    public  ICollection<Item> Items { get; set; }
    [ForeignKey("UserId")]
    public virtual User User { get; set; }
}

用户实体

public class User:BaseEntity
{
    public string Name { get; set; }
    public string Surname { get; set; }
    public string Gsm { get; set; }
    public string Email { get; set; }
    public virtual ICollection<ItemList> ItemLists{ get; set; }
}

我的 DTO

public class TopItemsForUsers
{
    [BsonRepresentation(BsonType.ObjectId)]
    [BsonId]
    public string ItemId { get; set; }
    public string UserId { get; set; }
    public int Quantity { get; set; }
}

我的物品库

var query = _context.Items.Include(l => l.ItemLists)
            .GroupBy(g => g.ItemLists)
            .Select(z => new TopItemsInLists { ItemId = z.Key.ToString(), Quantity = z.Count() })
            .OrderByDescending(z => z.Quantity)
            .Take(10);

我想要获得用户列表中非常重要的产品 我哪里做错了?如果大家有其他建议

试试这个查询。希望我理解正确。

var query = 
    from u in _context.Users
    from il in u.ItemLists
    from i in il.Items
    group i by new { UserId = u.Id, ItemId = i.Id } into g 
    select new TopItemsInLists
    {
        UserId = g.Key.UserId.ToString(), 
        ItemId = g.Key.ItemId.ToString(), 
        Quantity = g.Count()
    };

query = query
    .OrderByDescending(z => z.Quantity)
    .Take(10);