实体框架-在其集合中与一个实体一起选择集合

时间:2019-05-18 04:25:37

标签: entity-framework entity-framework-core

我在C#中有两个实体。一个是Box。另一个是Ball

Ball必须属于Box。这意味着BoxId上有一个Ball

public class Box
{
    public int Id { get; set; }
    public IEnumerable<Ball> Balls { get; set; }
}

public class Ball
{
    public int Id { get; set; }

    public int BoxId { get; set; }
    public Box Box { get; set; }

    public string Color { get; set; }
    public DateTime CreationTime { get; set; }
}

现在,我需要获得一些装有最新球的盒子,因为我需要知道它的颜色。

我已经尝试过这种方式:


// Runs slow because there is too many balls.
var boxes = await Boxes
.Where(somecondition)
.Include(t => t.Balls)
.ToListAsync()

foreach (var box in boxes)
{
    // Get the color which I only need.
    box.Balls.OrderByDesending(t => t.CreationTime).First().Color;
}

但是这样做将查询数据库中的所有球。现在有很多球(大约1000万个),因此查询速度很慢。

我只需要最后一个插入的框。我该怎么办?

1 个答案:

答案 0 :(得分:1)

您可以尝试使用“选择”并仅获取“球”的最后一条记录,如下所示。

另外,当我们使用Select时,我们可以删除.include,因为它在这里没有任何作用。

var boxes = await Boxes
            .Where(somecondition)
            .Select(t => new Box(){
              Id = t.Id,
              Balls = t.Balls.OrderByDescending(x => x.CreationTime)
                         .Take(1)
            })               
            .ToListAsync()