Reputation: 1002
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
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
Reputation: 26737
var user = Context.Accounts.SinlgeOrDefault(user => user.UserName=="yourValue");
if(user!=null)
{
// you can safely access the user properties here
}
Upvotes: 3