TheKingPinMirza
TheKingPinMirza

Reputation: 8912

Error in linq statement

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

Answers (4)

Mukesh Kalgude
Mukesh Kalgude

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

Sanjeev S
Sanjeev S

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

Nam B&#236;nh
Nam B&#236;nh

Reputation: 422

I would use:

string UserId = Context.Users.Where(x => x.UserName == username).Select(s => s.Id).DefaultIfEmpty(String.Empty).FirstOrDefault();

Upvotes: 0

daryal
daryal

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

Related Questions