Hello Im trying to compile this code it works fine with the DataType int Id but I tried to use Guid DataType and I got an error in the operation == part (Cannot be applied to operands of type 'Guid' and 'int') I don't know how to fix it and I don't know why its not working
public async Task<ServiceResponse<GetCharacterDto>> UpdateCharacter(UpdateCharacterDto updatedCharacter)
{
ServiceResponse<GetCharacterDto> response = new ServiceResponse<GetCharacterDto>();
try
{
var character = await _context.Characters
.Include(c => c.User)
.FirstOrDefaultAsync(c => c.Id == updatedCharacter.Id);
if (character.User.Id == GetUserId())
{
character.Name = updatedCharacter.Name;
character.Intelligence = updatedCharacter.Intelligence;
await _context.SaveChangesAsync();
response.Data = _mapper.Map<GetCharacterDto>(character);
}
else
{
response.Success = false;
}
}
catch (Exception ex)
{
response.Success = false;
}
return response;
}
}
CodePudding user response:
I used GUID many times and compared with different ways .A Guid is a 128 bit integer which represent as alphnumeric value . They are incompatible for comparison.
For Eample
interger value = 123
Guid Value=01e75c83-c6f5-4192-b57e-7427cec5560d
You can do by these ways
By ToString()
If(id.ToString() == guid.ToString() )
{
// logic
}
CompareTo
:-Recommended approach
if any of property is not guid then convert into guild using `Guid.Parse(value)' then use CompareTo
if(guid.CompareTo(id) == 0)
{
// logic
}
I dont know this exception due to statement in linq or if (character.User.Id == GetUserId())
statement but you can use these statement both places
Like This
// I am assuming that both are GUID Type
.FirstOrDefaultAsync(c => c.Id.CompareTo(updatedCharacter.Id) ==0);
OR
// I am assuming that both are GUID Type
if (character.User.Id.CompareTo(GetUserId()) == 0)`