Search code examples
c#sql.netlinqentity-framework-6

Return record with max column value using Entity Framework 6


Trying to get record with max datetime value for ReceivedDateTime column, however data set should be pre-filtered by some Id column (not unique). Solved this way:

using (var db = new SystemEntities())
{
    var records = db.Table.Where(p => p.Id == Id);
    var record = records.Where(p => p.ReceivedDateTime == records.Max(r => r.ReceivedDateTime)).FirstOrDefault();
    if(record != null)
    {

    }
}

Is there more beautiful, simpler and shorter implementation, notation? Thanks!


Solution

  • You can simplify like the following using OrderByDescending:

    using (var db = new SystemEntities())
    {
        var record = db.Table.Where(p => p.Id == Id).OrderByDescending(x => x.ReceivedDateTime).FirstOrDefault();
        if(record != null){}
    }