Home > Blockchain >  How to copy the values of an object to another object without doing it manually
How to copy the values of an object to another object without doing it manually

Time:08-14

I have this Problem with the put request in asp Net core.

var data = await _service.GetReceiptOrderByIdAsync(request.Id, false, cancellationToken);
        if (data == null)
            throw new NotFoundException(nameof(ReceiptOrder), request.Id);
        
        data = _mapper.Map<ReceiptOrder>(request.ReceiptOrderForUpdateDto);
        
        await _service.SaveChangeAsync(cancellationToken);

the put request is not successful because the ef core is not detecting changes, but if I do it manually it get successful. Example:

var data = await _service.GetReceiptOrderByIdAsync(request.Id, false, cancellationToken);
        if (data == null)
            throw new NotFoundException(nameof(ReceiptOrder), request.Id);
        
        data.IsPaid = true;
                await _service.SaveChangeAsync(cancellationToken);

the problem is when I do this code:

        data = _mapper.Map<ReceiptOrder>(request.ReceiptOrderForUpdateDto);

the data object gets the reference of the other object so ef core is not detecting the changes.

any help please?

CodePudding user response:

It's not documented the best, but Automapper has Map call for copying data from one instance to another:

var data = await _service.GetReceiptOrderByIdAsync(request.Id, false, cancellationToken);
if (data == null)
    throw new NotFoundException(nameof(ReceiptOrder), request.Id);
    
_mapper.Map(request.ReceiptOrderForUpdateDto, data);
    
await _service.SaveChangeAsync(cancellationToken);

This will copy values from your DTO into the existing data object. The problem with your original code is that data = _mapper.Map(...) will replace the reference to the entity so nothing is saved since you aren't updating the tracked entity, but replacing the reference with a new instance of the class built by Automapper.

CodePudding user response:

You can use Object.MembershipClone(), but it has some significant limitations. docs

  • Related