haind
haind

Reputation: 1002

LINQ Check exist Username then get that User's ID

I have an Account table:

    table Account
    (
    UserId int identity(1, 1),
    UserName nvarchar(20) not null unique,
    Password nvarchar(20) not null
    )

By using LINQ. Whether I can check exist UserName for an account then. And it's true then get UserId for that account (I'm use ASP MVC 4 with Entity Framework)

Upvotes: 0

Views: 6870

Answers (2)

Andre Figueiredo
Andre Figueiredo

Reputation: 13425

When using Linq to query from DB, I prefer to use query expression, that is closer to SQL notation than Lambda notation.

Given that you have the username:

try {
    int userId = (from x in context.Account
                   where x.UserName == username
                   select x.UserId).SingleOrDefault());

    if (userId > 0){
        // user exists
    }
    else {
        // user does not exist
    }
}
catch(InvalidOperationException ex){
    // has more than one element
}

Upvotes: 3

Massimiliano Peluso
Massimiliano Peluso

Reputation: 26737

var user = Context.Accounts.SinlgeOrDefault(user => user.UserName=="yourValue");
if(user!=null)
{
// you can safely access the user properties here
}

Upvotes: 3

Related Questions