LINQ to SQL MAX in WHERE clause

I am new to Linq, so, as expected, I ran into difficulties. I am trying to achieve this:

SELECT id, name, password
FROM users u
WHERE u.id = (SELECT MAX(u1.id) FROM users u1);

My Linq:

var dbUsers = from u in context.Users
              where u.Id == (context.Users.Max(u1 => u1.Id))
              select u;

But I always end up with the following exception:

Unable to create a constant value of type "Bla.Users". Only primitive types (such as Int32, String, and Guid) are supported in this context.

Here is the user class:

public class Users
    {
        [Key]
        public int Id { get; set; }
        public string Name { get; set; }
        public string Password { get; set; }
    }
}

Here is my context class:

 public class EFDbContext : DbContext
    {
        public DbSet<User> Users{ get; set; }
    }
+5
source share
5 answers

You need to select a property ID

var dbUsers = from u in context.Users
              where u.Id == (context.Users.Select(u1 => u1.Id).Max())
              select u;
+7
source

I usually use LINQing in lambda format ...

var dbUsers = DataContext.Users
    .Where(u => u.Id == (DataContext.Users.Max(u1 => u1.Id)))
    .Select(u => new
    {
       Id = u.Id,
       Name = u.Name,
       Password = u.Password
    });

If you need an understanding format ...

var dbUsers = from u in DataContext.Users
    where u.Id == (DataContext.Users.Max(u1 => u1.Id))
    select new 
    {
       Id = u.Id,
       Name = u.Name,
       Password = u.Password
    };
+1
source

let:

var dbUsers = from u in context.Users
              let int maxId = context.Users.Max(u1 => u1.Id)
              where u.Id == maxId
              select u;
+1

, , :

var dbUser = (from u in context.Users
              orderby u.Id descending).FirstOrDefault()
+1

-:

var dbUser = context.Users.First(u => u.Id== (context.Users.Select(u2
=> u2.Id).Max()));

var dbUser = context.Users.OrderByDescending(u => u.Id).FirstOrDefault();
0

All Articles