LINQ join in lambda with most recent date
我正在尝试对表"Personen"进行 linq 查询并加入表"Leners"。
从表"Leners"中,如果有的话,我想要最新的项目。
在 SQL 中我会这样做:
1 2 3 4 5 6 7 | select p.*, l.* from dbo.Personen p left outer join dbo.Leners l on l.LenerId = (select top 1 LenerId from dbo.Leners lt where lt.PersoonId = p.PersoonId order by lt.Vanaf desc) |
我怎样才能用 linq 做到这一点?
我想在 lambda 表达式中执行此操作,因为它取决于选择。
1 2 3 4 5 6 7 8 9 10 | using (var db = new DbContext()) { var query = from p in db.Personen select p; if (someSelection != null) { query = ? } } |
这些是表格:(EF 代码在前)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | [Table("Personen")] public class Persoon { [Key] public int PersoonId { get; set; } [StringLength(50)] [Required] public string Naam { get; set; } } [Table("Leners")] public class Lener { public int LenerId { get; set; } public int? PersoonId { get; set; } [ForeignKey("PersoonId")] public virtual Persoon Persoon { get; set; } public DateTime Vanaf { get; set; } } |
您的 LINQ 查询应如下所示:
1 2 3 4 5 | var query2 = from p in dbo.Personen let l = dbo.Leneren .OrderByDescending(lt => lt.Vanaf) .FirstOrDefault(lt => lt.PersoonId == p.PersoonId) select new { p, l } |
但是,您不能将它分配回您的
1 2 | var query = from p in db.Personen select p; |