一对多EF查询以获取最新的许多行

时间:2013-07-25 21:44:18

标签: entity-framework entity-framework-4 linq-to-entities ef-code-first

我有以下POCO:

public class TrackToken
{
    [Required, Key]
    public int ID { get; set; }

    [MaxLength( 500 )]
    public string Comment { get; set; }

    [Required]
    public DateTime CreationTime { get; set; }

    public virtual ICollection<TrackLog> Logs { get; set; }
}

public class TrackLog
{
    [Required, Key]
    public int ID { get; set; }

    [Required]
    public TrackToken Parent { get; set; }

    [Required]
    public DateTime Time { get; set; }

    [Required]
    public int ServerID { get; set; }
}

我希望能够创建一个可以返回每个TrackToken的EF LINQ查询,并加入该TrackToken的最新TrackLog。

我尝试过代码:

TrackTokens
.Select( t => new
{
    ID = t.ID,
    Comment = t.Comment,
    CreationTime = t.CreationTime,

    RecentLog = t.Logs.OrderByDescending( l => l.Time ).FirstOrDefault(),
} );

但是在执行查询的某个地方,我得到了

EntityCommandCompilationException: An error occurred while preparing the command definition. See the inner exception for details.

InnerException: NotSupportedException: Specified method is not supported.

这似乎与FirstOrDefault的使用有关。

我也尝试了类似的东西,但我不确定如何获取ServerID列

TrackTokens
.Select( t => new
{
    ID = t.ID,
    Comment = t.Comment,
    CreationTime = t.CreationTime,

    LastSeen = t.Logs.Max( l => l.Time ),
    LastServerID = // how do I get the ServerID column of the most recent record?
} );

在这种关系上执行查询的首选方法是什么?

2 个答案:

答案 0 :(得分:1)

您可以使用以下方式在LastServerID语句中获取Select

LastServerID = t.Logs.OrderByDescending(l => l.Time)
    .Select(l => l.ServerID).FirstOrDefault()

(可能你必须使用Select(l => (int?)l.ServerID)使返回类型为空,才能将案例记入a TrackToken没有任何TrackLog的帐户。同样可能是时间: Max(l => (DateTime?)l.Time)

它适用于SQL Server。但是,真正的问题似乎是EF的MySQL提供程序在投影中不支持FirstOrDefault(也提到了here)。

答案 1 :(得分:0)

尝试这样的事情......

using (var context = new YourContext())
{
    context.TrackTokens.OrderByDecending(t => t.LastServerID).FirstOrDefault();
}
相关问题