0

I have a problem that I cannot solve. When Im trying to update one field in the db called 'Introduction', I get this message from API:

System.ArgumentNullException: Value cannot be null. (Parameter 'entity') at Microsoft.EntityFrameworkCore.Utilities.Check.NotNull[T](T value, String parameterName) at Microsoft.EntityFrameworkCore.DbContext.Entry[TEntity](TEntity entity) at ClinicAPIv1.Data.UserRepository.Update(ClinicUser clinicUser) in E:\Users\User\Desktop\Clinic\ClinicAPIv1\ClinicAPIv1\Data\UserRepository.cs:line 61 at ClinicAPIv1.Controllers.UsersController.UpdateDoctor(DoctorUpdateDTO doctorUpdateDTO) in E:\Users\User\Desktop\Clinic\ClinicAPIv1\ClinicAPIv1\Controllers\UsersController.cs:line 74 at lambda_method34(Closure , Object ) at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Logged|12_1(ControllerActionInvoker invoker) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Logged|17_1(ResourceInvoker invoker) at Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger) at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context) at ClinicAPIv1.Middleware.ExceptionMiddleware.InvokeAsync(HttpContext context) in E:\Users\User\Desktop\Clinic\ClinicAPIv1\ClinicAPIv1\Middleware\ExceptionMiddleware.cs:line 30

I understand that the problem is with the update function in my repository:

public void Update(ClinicUser clinicUser)
    {
        _context.Entry(clinicUser).State = EntityState.Modified;
    }

line 61 is

_context.Entry(clinicUser).State = EntityState.Modified;

Controller Put method looks like:

   [HttpPut]
public async Task<ActionResult> UpdateDoctor(DoctorUpdateDTO doctorUpdateDTO)
    {
        var email = User.FindFirst(ClaimTypes.Name)?.Value;
        var user = await _userRepository.GetUserByEmail(email);

        _mapper.Map(doctorUpdateDTO, user);

        _userRepository.Update(user);

        if (await _userRepository.SaveAllAsync()) return NoContent();

        return BadRequest("Failed to update Doctor Profile :(");
    }

Line 74 is

_userRepository.Update(user);

DoctorUpdateDTO:

public class DoctorUpdateDTO
{
    public string Introduction { get; set; }
}

Mapper:

public class AutoMapperProfiles : Profile
{
    public AutoMapperProfiles()
    {
        CreateMap<ClinicUser, MemberDTO>()
            .ForMember(dest => dest.PhotoUrl, opt => opt.MapFrom(
                src => src.Photos.FirstOrDefault().Url));
        CreateMap<Photo, PhotoDTO>();
        CreateMap<DoctorUpdateDTO, ClinicUser>();
    }
}

GetUserByEmail:

public async Task<ClinicUser> GetUserByEmail(string email)
    {
        return await _context.clinicUsers
            .Where(x => x.TemporaryRole == "Doctor")
            .Include(p => p.Photos)
            .SingleOrDefaultAsync(x => x.Email == email);
    }

ClinicUser:

public class ClinicUser
{
    public int Id { get; set; }
    public string Email { get; set; }
    public string Name { get; set; }
    public string LastName { get; set; }
    public string Specialization { get; set; }
    public string Introduction { get; set; }
    public string City { get; set; }
    public string Country { get; set; }
    public string PhoneNumber { get; set; }
    [JsonIgnore]
    public ICollection<Photo> Photos { get; set; }
    public string TemporaryRole { get; set; }
}

Please help me solve the problem

2
  • So. When you debugged this, at which point was the object state not what you expected? Commented Dec 1, 2021 at 23:24
  • You should try to include unit tests in your code. solves these problems a lot. In anyway, check the EntityState.Modified to see if it returns null. Commented Dec 1, 2021 at 23:28

1 Answer 1

0

Chain ReverseMap after CreateMap calls in your AutoMapperProfiles. Get more information here.

Sign up to request clarification or add additional context in comments.

5 Comments

I tried to use reverse mapping, but the error is the same :(
Can you please update your question with ClinicUser definition?
Done, its a class witch db fields
If you break at line _userRepository.Update(user) , does your user has updated Introduction value? Try to debug and see if mapping is properly done.
Thanks for help, I solved this thanks to you ;))))))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.