This works, but requires me to execute the extra .ToList () too early, so it is slow ...
public static Expression<Func<Admission, int?>> CurrentHouseSequence()
{
return a => a.Person.Locations.OrderByDescending(l => l.TransferDate).DefaultIfEmpty(new Location()).Select(s => s.House != null ? s.House.Seq : null).FirstOrDefault();
}
var getCurrentHouseSequence = AdmissionRoot.CurrentHouseSequence().Compile();
List<Admission> adms = Db.Admissions
.ToList()
.OrderBy( a => getCurrentHouseSequence(a))
.Take(100)
.ToList();
Then I tried the following: insert the extracted source link from the function directly into orderby, but get an exception at runtime
An object or complex type 'DataContext.Location' cannot be constructed in a LINQ to Entities query.
List<Admission> adms = Db.Admissions
.OrderBy( a => a.Person.Locations.OrderByDescending(l => l.TransferDate).DefaultIfEmpty(new Location()).Select(s => s.House != null ? s.House.Seq : null).FirstOrDefault())
.Take(100)
.ToList();
... Does anyone have any ideas how this can be achieved, please ???
so that was my final decision (thanks to Rob) ...
List<Admission> adms = Db.Admissions
.OrderBy(a => a.Person.Locations.Any()
? a.Person.Locations.OrderByDescending(l => l.TransferDate)
.Select(l => l.House != null ? l.House.Seq : null)
.FirstOrDefault()
: null)
.Take(100)
.ToList();
source
share