[c#] How do I get the max ID with Linq to Entity?

I have a table User which has an identity column UserID, now what is the correct Linq to Entity line of code that would return me the max UserID?

I've tried:

using (MyDBEntities db = new MyDBEntities())
{
    var User = db.Users.Last();
    // or
    var User = db.Users.Max();

    return user.UserID;
}

but Last and Max don't seem to be supported.

Any ideas?

This question is related to c# linq entity-framework linq-to-entities

The answer is


The best way to get the id of the entity you added is like this:

public int InsertEntity(Entity factor)
{
    Db.Entities.Add(factor);
    Db.SaveChanges();
    var id = factor.id;
    return id;
}

Note that none of these answers will work if the key is a varchar since it is tempting to use MAX in a varchar column that is filled with "ints".

In a database if a column e.g. "Id" is in the database 1,2,3, 110, 112, 113, 4, 5, 6 Then all of the answers above will return 6.

So in your local database everything will work fine since while developing you will never get above 100 test records, then, at some moment during production you get a weird support ticket. Then after an hour you discover exactly this line "max" which seems to return the wrong key for some reason....

(and note that it says nowhere above that the key is INT...) (and if happens to end up in a generic library...)

So use:

Users.OrderByDescending(x=>x.Id.Length).ThenByDescending(a => a.Id).FirstOrDefault();


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.


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();

The best way to get the id of the entity you added is like this:

public int InsertEntity(Entity factor)
{
    Db.Entities.Add(factor);
    Db.SaveChanges();
    var id = factor.id;
    return id;
}

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.


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);

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();

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.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to linq

Async await in linq select How to resolve Value cannot be null. Parameter name: source in linq? What does Include() do in LINQ? Selecting multiple columns with linq query and lambda expression System.Collections.Generic.List does not contain a definition for 'Select' lambda expression join multiple tables with select and where clause LINQ select one field from list of DTO objects to array The model backing the 'ApplicationDbContext' context has changed since the database was created Check if two lists are equal Why is this error, 'Sequence contains no elements', happening?

Examples related to entity-framework

Entity Framework Core: A second operation started on this context before a previous operation completed EF Core add-migration Build Failed Entity Framework Core add unique constraint code-first 'No database provider has been configured for this DbContext' on SignInManager.PasswordSignInAsync The instance of entity type cannot be tracked because another instance of this type with the same key is already being tracked Auto-increment on partial primary key with Entity Framework Core Working with SQL views in Entity Framework Core How can I make my string property nullable? Lazy Loading vs Eager Loading How to add/update child entities when updating a parent entity in EF

Examples related to linq-to-entities

How to add a default "Select" option to this ASP.NET DropDownList control? LEFT JOIN in LINQ to entities? How to get first record in each group using Linq Linq to Entities join vs groupjoin The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties Linq where clause compare only date value without time value The specified type member is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported SQL to Entity Framework Count Group-By LINQ to Entities does not recognize the method The cast to value type 'Int32' failed because the materialized value is null