【问题标题】:Linq Group by Related EntitiesLinq 集团(按关联实体)
【发布时间】:2021-12-14 06:50:02
【问题描述】:

我想获得他们列表中最多的项目 我要运行的 sql 查询

select 
    i.Id, 
    count(*) as count
from Items
    inner join ItemItemList il on i.Id = il.ItemsId
group by i.Id
order by count desc

物品实体

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; }
}

我的 DTO

public class TopItemsInLists
{
    [BsonRepresentation(BsonType.ObjectId)]
    [BsonId]
    public string ItemId { 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);

我想在 ItemLists 中找到最多的项目。 我在哪里做错了?如果有人有其他建议

【问题讨论】:

    标签: asp.net-mvc linq .net-core


    【解决方案1】:

    您必须按 Id 分组,而不是按集合属性分组。就像在 SQL 中一样。但在此之前,您必须将记录乘以 SelectMany

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

    但我建议对这种更接近 SQL 的结构使用查询语法:

    var query = 
        from i in _context.Items
        from il in i.ItemLists 
        group i by i.Id into g 
        select new TopItemsInLists
        {
            ItemId = g.Key.ToString(), 
            Quantity = g.Count()
        };
    
    query = query
        .OrderByDescending(z => z.Quantity)
        .Take(10);
    

    【讨论】:

    • 好吧,除此之外,如果我想以用户为基础,我该怎么做。我的用户实体中有这样的属性。我是否需要从公共虚拟 ICollection ItemLists{ 获取另一个?放; }
    • 可能,另一个from 将添加另一个join 并应用记录乘法。
    • await (from l in _context.ItemLists from i in l.Items from u in _context.Users group new { i, u } by new TopItemsForUsers { ItemId = i.Id.ToString(), UserId = u.Id.ToString() } 进入查询
    • 从这种方式执行时出现错误。 “System.InvalidOperationException”。我在哪里做错了?
    • 分组键错误。创建另一个问题。
    猜你喜欢
    • 1970-01-01
    • 2021-12-14
    • 1970-01-01
    • 2016-02-07
    • 2018-04-09
    • 2018-07-28
    • 1970-01-01
    • 1970-01-01
    • 2012-01-16
    相关资源
    最近更新 更多