Reputation: 8912
I am getting error for following LINQ statement
Error
"Can't convert implicitly type bool to string
string UserId = Context.Users.Where(x => x.UserName == username).FirstOrDefault(x => x.Id);
What is wrong here?
Upvotes: 0
Views: 126
Reputation: 4844
If you want only id like this
string UserId = Context.Users.Where(x => x.UserName == username).Select(g=> g.Id.ToString()).FirstOrDefault();
If you want users object like this
var Usersobj=Context.Users.Where(x => x.UserName == username).FirstOrDefault();
Upvotes: 5
Reputation: 626
x=>x.Id is used for enumerating over the collection and applying the condition to check which one matches and then returns the first match.
FirstOrDefault<Tsource>
if <Tsource>
is empty the first element in source.
Here FirstOrDefault taken only by passing the id, so use x=>x.Id==id
var user = Context.Users.Where(x => x.UserName == Username ).FirstOrDefault(x=>x.Id==id)
or
string UserId = Context.Users.Where(x => x.UserName == Username ).FirstOrDefault(x=>x.Id==id).ToString();
Upvotes: 0
Reputation: 422
I would use:
string UserId = Context.Users.Where(x => x.UserName == username).Select(s => s.Id).DefaultIfEmpty(String.Empty).FirstOrDefault();
Upvotes: 0
Reputation: 14919
You need to check whether a user exists with the provided username, otherwise it will throw a null reference exception;
string id = string.Empty;
User user = Context.Users.FirstOrDefault(x => x.UserName == username);
if(user != null)
{
id=user.Id.ToString(); //if id is already a string no need for ToString()
}
or single line with c# 6;
string userId = Context.Users.FirstOrDefault(x => x.UserName == username)?.Id.ToString();
Upvotes: 3