【问题标题】:Get top n records with top m of relative table in Entity Framework获取实体框架中相对表前 m 的前 n 条记录
【发布时间】:2015-09-19 14:53:49
【问题描述】:

我有一张桌子Categories 和Products。一个类别可以有多个产品,我想获得每个产品的 TOP 5 产品和 TOP 3 类别。我试过了

entity.Categories.Include("Products").Take(3)

但输出是 3 个类别及其下的所有产品。我试过了

entity.Categories.Take(5).Include("Products").Take(3)

当然它不会起作用,因为Include 不能在Take 中调用。那么解决方案可能是什么?请提出建议。

【问题讨论】:

  • 您想要每个前 3 个类别的前 5 个产品,或者您想要所有 3 个顶级类别中的前 5 个产品?
  • 无论如何,数字不是我关心的。你能建议查询吗?
  • @ImadoddinIbnAlauddin 你看过这个问题吗stackoverflow.com/questions/17939528/…
  • @Arvaan 兄弟。我已经解决了。

标签: c# asp.net asp.net-mvc entity-framework linq


【解决方案1】:

终于解决了

var result = entity.Categories.Select
                         (
                            cats => new
                                {   
                                    cats.CategoryName,
                                    cats.Description,
                                    Products = cats.Products.Take(3)
                                }
                         ).Take(5);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多