Using max() function with entity framework throws an exception

entity-framework max

Question

So I need to get the max value of a column (or the last one) using entity framework and both of these queries throw exceptions:

(The ID I'm trying to retrieve is of type varchar, but it works in raw sql, I think it should work here too)

This one:

string maxCurrentID = db.reservations.Max().ReservationID;

Throws this:

The specified method 'EntityClub_.reservacion Maxreservacion' on the type 'System.Linq.Queryable' cannot be translated into a LINQ to Entities store expression because no overload matches the passed arguments.

and this one:

 string maxCurrentID = db.reservations.LastOrDefault().ReservationID;

LINQ to Entities does not recognize the method 'EntityClub_.reservacion LastOrDefaultreservacion' method, and this method cannot be translated into a store expression.

How can I obtain the expected values?

1
1
9/5/2013 12:43:16 PM

Accepted Answer

You aren't asking for the highest ReservationID, you're trying to get the highest Reservation, and getting its ReservationID. EF does not understand what "the highest Reservation" means.

var maxReservationID = db.reservations.Max(r => r.ReservationID);

or

var maxReservationID = db.reservations.Select(r => r.ReservationID).Max();

should work.

7
1/13/2013 8:18:19 AM

Popular Answer

var maxReservationId=db.reservations.Max(u =>(int?)u.ReservationID) ?? 0;

if there is no data in table it replaces null with 0



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow