如何有效地进行亲子配对?

时间:2014-03-04 23:32:40

标签: linq entity-framework-6

给定一个这样的表结构,在DbContext中公开Tops,Mids和Bots:

Top { long TopId; IList<Mid> Mids; ... }
Mid { long MidId; long TopId; IList<Bot> Bots; ...}
Bot { long BotId, long MidId; DataTime Timestamp; string Data; ...}

如何编写一个有效的查询来为整个Mid表提供每个Mid的第一个Bot项目。 “first”是指具有最小时间戳的那个。我更喜欢这样的事情:

var results = _db.Mids.Select(m => new {Mid = m, Bot = 
       _db.Bots.Where(b => b.MidId = m.Id)
          .OrderBy(b => b.Timestamp).FirstOrDefault()});

1 个答案:

答案 0 :(得分:1)

简单地写一下:

var results = _db.Mids.Select(m => new
{
    Mid = m,
    Bot = m.Bots.OrderBy(b => b.Timestamp).FirstOrDefault()
});

您可以看到使用results.ToString()

生成的SQL查询
相关问题