In my current .net core mvc project with entity framework, I use automapper with DI. In my edit method I need to update the domain model using a viewmodel. This is where I use automapper. But the viewmodel contains only a few properties of the domainmodel. The other properties should be retained, however, they are set to null or defaults when I apply the _context.Update(modelToSubmit); How can I update only the fields in the domain model that I actually want to change (those that are in the viewmodel)?
The way its currently done in this project is by adding all the properties in the viewmodel, and using the @Html.HiddenFor tag in the view, which I regard as a bad practice, and I want to get rid of.
I have a single line of code for the mapping:
DomainModel model = _mapper.Map<DomainModel>(viewModel);
Edit: I now have (based on answer below):
DatabaseModel originalRecord = _unitOfWork.DatabaseModel.Get(id);
var mappedModel = _mapper.Map<ViewModel>(originalRecord);
var newDto = _mapper.Map<ViewModel, DataBaseModel>(returnedViewModel, originalRecord);
originalRecord = _mapper.Map<ViewModel, DatabaseModel>(mappedModel);
_unitOfWork.DatabaseModel.Update(originalRecord);
My mappingprofile:
CreateMap<ViewModel, DatabaseModel>()
.IgnoreAllPropertiesWithAnInaccessibleSetter()
.ForPath(dest => dest.ID, opt => opt.Ignore())
.ForPath(dest => dest.Deadline, opt => opt.Ignore())
.ForPath(dest => dest.RecordCreated, opt => opt.Ignore())
.ForPath(dest => dest.Status, opt => opt.Ignore())
.ReverseMap();
When I save the model on the website, I get this error:
Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException: Database operation expected to affect 1 row(s) but actually affected 0 row(s).
The query to retrieve originalRecord has a AsNoTracking() method, but it still throws this error.