1

I have the following POCOs:

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

I'd like to be able to make a EF LINQ query that can return every TrackToken, and join with the most recent TrackLog for that TrackToken.

I've tried code like:

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

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

But somewhere along the line of executing the query, I get

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

InnerException: NotSupportedException: Specified method is not supported.

Which appears to be related to the usage of FirstOrDefault.

I've also tried something similar to this, but I'm unsure of how to get the ServerID column

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?
} );

What's the go-to method of performing a query on this sort of relationship?

4

2 回答 2

1

您可以使用以下方法LastServerID在您的Select声明中获取:

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

(可能您必须使返回类型可以为 nullSelect(l => (int?)l.ServerID)才能将案例记入 aTrackToken没有任何TrackLog. 的帐户。当时可能相同Max(l => (DateTime?)l.Time):)

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

于 2013-07-26T16:30:57.647 回答
0

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

using (var context = new YourContext())
{
    context.TrackTokens.OrderByDecending(t => t.LastServerID).FirstOrDefault();
}
于 2013-07-26T14:19:24.557 回答