Search code examples
c#linqlinq-to-entities

Linq: Order by date and Find the first element


I want to query a datatable where i select list of rows based on some data and order the rows by date and get the row with latest date. This is what I did

var propertyValueId = _dbSis.Set<PropertyValue>()
                            .Where(m => m.PropertyInstanceId == id)
                            .OrderBy(z => z.TimeStamp);
var pvalueId = propertyValueId.ElementAtOrDefault(0);

but I get error on propertyValueId.ElementAtOrDetault(0);

LINQ to Entities does not recognize the method 'Sorama.DataModel.SIS.Configuration.PropertyValue ElementAtOrDefault[PropertyValue](System.Linq.IQueryable`1[Sorama.DataModel.SIS.Configuration.PropertyValue], Int32)' method, and this method cannot be translated into a store expression.

How can I achieve what I just expected, and how can i solve the error?


Solution

  • Seems strange that FirstOrDefault() does not work.

    var pvalueId = propertyValueId.FirstOrDefault();
    

    Should that not be supported:

    var pvalueId = propertyValueId.Take(1).SingleOrDefault();
    

    Or, if for some bizarre reason your L2EF provider cannot handle FirstOrDefault, Take, or SingleOrDefault, you can brute force it:

    PropertyValue pvalueId = null;
    foreach (var pv in propertyValueId)
    {
        pvalueId = pv;
        break;
    }