簡體   English   中英

實體框架6-基於導航屬性的GroupBy

[英]Entity Framework 6 - GroupBy on navigation properties

我正在使用Entity Framework 6(EF 6),並且具有以下模型:

public class Engine {
    public int Id { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Car> Cars { get; set; }
}

public class Car {
    public int Id { get; set; }
    public string Name { get; set; }

    public virtual Engine Engine { get; set; }
    public virtual Purchase Purchase { get; set; }
}

public class Purchase {
    public int Id { get; set; }
    public DateTime Created { get; set; }

    public virtual ICollection<Car> Cars { get; set; }
}
  • Engine <-> Car (一對多關系)
  • Purchase <-> Car (一對多關系)

如何確定購買最多的發動機? 我需要發動機的有序列表(降序)以及購買頻率。

我在導航屬性以及如何適當地分組/聚合方面存在一些問題。

謝謝

嘗試這個:

        return
            (from car
                 in this.Context.Cars
                    where car.Purchase != null
                    group car by car.Engine into g
               select new { EngineName = g.Key.Name, CountSold = g.Count()})
            .OrderByDescending(x => x.CountSold)
            .ToList();

另外,請在這里看看。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM