Reputation: 81
I get error message:
Operator '==' cannot be applied to operands of type 'int' and 'string'
var user = _db.ApplicationUsers.FirstOrDefault(u => u.Id == Id);
var userRole = _db.UserRoles.ToList();
var roles = _db.Roles.ToList();
var role = userRole.FirstOrDefault(u => u.UserId == user.Id);
if (role != null)
{
user.Role = roles.FirstOrDefault(u => u.Id == user.Role).Id;
}
Ok, I get the point that I have from left side int
and right side string
. This is clear, but when I try to convert all query to string like
Object reference not set to an instance of an object.
if (role != null)
{
user.Role = roles.FirstOrDefault(u => u.Id.ToString() == user.Role).Id.ToString();
}
I also try something like
if (role != null)
{
user.Role = roles.FirstOrDefault(u => u.Id == int.Parse(user.Role)).Id.ToString();
}
And it throw exception:
ArgumentNullException: Value cannot be null. (Parameter 's')
What I made wrong here ? Where is the mistake ?
Upvotes: 0
Views: 749
Reputation: 47
When you compare strings don't do '==' but use String.Equals(string a, string b) this will take care of some problems for you. Then you need to check if the returned object is not null. If the FirstOrDefault Function returns null you do not have an object with the criteria in that collection.
Something like this should get you there:
if (role != null)
{
foundRole = roles.FirstOrDefault(u => string.Equals(u.Id.ToString(), User.Role))
if(foundRole != null){user.Role = foundRole.Id.ToString())
}
Another Hint: take care of the names of the variables. For me this seems very confusing:
Hope this helps!
Upvotes: 1