Alex Terreaux
Alex Terreaux

Reputation: 1941

Using max() function with entity framework throws an exception

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?

Upvotes: 1

Views: 11737

Answers (2)

sanjeet
sanjeet

Reputation: 1508

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

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

Upvotes: 19

user743382
user743382

Reputation:

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.

Upvotes: 7

Related Questions