LINQ使用最近的日期加入lambda

时间:2013-03-29 12:34:48

标签: c# linq entity-framework lambda ef-code-first

我正在尝试对表'Personen'进行linq查询并加入表'Leners' 从表'Leners'我想要最新的项目(如果有的话)。

在SQL中,我会这样做:

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表达式中执行此操作,因为它取决于选择。

using (var db = new DbContext())
{
    var query = from p in db.Personen                        
                select p;

    if (someSelection != null)
    {
        query = ?
    }
}

这些是表格:( EF代码优先)

[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; }
}

1 个答案:

答案 0 :(得分:3)

您的LINQ查询应如下所示:

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 }

但是,您无法将其分配回query变量!

var query = from p in db.Personen                        
            select p;

queryIQueryable<Person>,因为您在此处选择Person项。您无法将其重新指定为IQueryable<AnotherType>