0

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)

haind
  • 1,000
  • 2
  • 16
  • 28

2 Answers2

3
var user = Context.Accounts.SinlgeOrDefault(user => user.UserName=="yourValue");
if(user!=null)
{
// you can safely access the user properties here
}
Massimiliano Peluso
  • 26,379
  • 6
  • 61
  • 70
3

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
}
Andre Figueiredo
  • 12,930
  • 8
  • 48
  • 74