How to select a row (object) based on the maximum field of Entity Framework 4.1

I am trying to get a row (object) based on max RollNumber , which is a long Datatype field . I expect it to return a null object if it is not there, so I used SingleorDefault . But it looks like my request is wrong (linq work is done here). here is the request:

 SchoolContextExpress db = new SchoolContextExpress(); Profile profile = db.Profiles.Where(p => p.RollNumber == db.Profiles.Max(r=>r.RollNumber)).SingleOrDefault(); 

thanks for this.

+7
source share
2 answers

To work with an empty RollNumber ...

 Profile profile = db.Profiles.Where(p => p.RollNumber !=0 && p.RollNumber == db.Profiles.Max(r=>r.RollNumber)).SingleOrDefault(); 

Or you can consider ...

 Profile profile = db.Profiles.Where(p => p.RollNumber == db.Profiles.Where(p1 => p1.RollNumber != 0).Max(r=>r.RollNumber)).SingleOrDefault(); 
+9
source

Another way to make the first answer:

 Profile profile = db.Profiles.OrderByDescending(p => p.RollNumber).FirstOrDefault(); 
+2
source

All Articles