Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the max ID with Linq to Entity?

People also ask

How to get max ID using LINQ query?

Select Max Value in linq to entities Characters. Where(o => o. UserID == UserID) . Max(o => o.

How to get max ID in c#?

One way is to make the PId Column auto increment. Other way it to get the max Pid value from Database increment it by 1 then insert it into the Database. You can refer this question as a reference.

How do you select records with Max ID that group by multiple columns in LINQ to SQL?

In SQL, it is very simple to do: SELECT * FROM [dbo]. [tblOrderDeliveryGroup] t1 WHERE [DeliveryGroupId] IN ( SELECT MAX([DeliveryGroupId]) FROM [dbo]. [tblOrderDeliveryGroup] t2 WHERE (t1.

Does LINQ work with Entity Framework?

Entity Framework Core uses Language-Integrated Query (LINQ) to query data from the database.


Do that like this

db.Users.OrderByDescending(u => u.UserId).FirstOrDefault();

try this

int intIdt = db.Users.Max(u => u.UserId);

Update:

If no record then generate exception using above code try this

int? intIdt = db.Users.Max(u => (int?)u.UserId);

var max = db.Users.DefaultIfEmpty().Max(r => r == null ? 0 : r.ModelID);

when there are no records in db it would return 0 with no exception.


NisaPrieto

Users user = bd.Users.Where(u=> u.UserAge > 21).Max(u => u.UserID); 

will not work because MAX returns the same type of variable that the field is so in this case is an INT not an User object.


In case if you are using the async and await feature, it would be as follows:

User currentUser = await db.Users.OrderByDescending(u => u.UserId).FirstOrDefaultAsync();