I have gone through some solutions provided here on SO like this. Basically I have a User class that has a lot of properties.
public class Users
{
[Key]
public Guid Id { get; set; }
[MaxLength(200)]
public string Username { get; set; }
public bool Enabled { get; set; }
public string Name { get; set; }
//...Many more properties
}
And UpdateUser() method to update the user. My issue is the method is long and doesn't look clean because of the many properties that are being updated.
public async Task<UpdateUserResponse> UpdateUser(UpdateUserRequest userRequest)
{
var user = await _userRepository.GetByIdAsync(userRequest.Id);
if (user == null)
throw new HttpException(HttpStatusCode.BadRequest, $"User does not exist");
user.EmailAddress = userRequest.EmailAddress;
user.Enabled = userRequest.Enabled;
user.Name = userRequest.Name;
user.SurName = userRequest.SurName;
//...many more properties which make this method to be long
// I attempted to do something like this which gave the error
// var usrObj = JsonConvert.DeserializeObject<Users>(JsonConvert.SerializeObject(userRequest));
// var res = await _userRepository.UpdateAsync(usrObj);
context.Entry(user).State = EntityState.Modified;
var result = await context.SaveChangesAsync();
//......
return response;
}
I tried to deserialize the userRequest object into type User but in the UpdateAsync() method, Entity Framework Core complains with the following message, which makes sense:
The instance of entity type 'Users' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked.
I'm looking for a cleaner way of doing this.