Menu

Configuring the AutoMapper property binding behaviour

When you map ViewModels to Entity model its not always one-to-one.

For example showing an item in the database in a details view can be one-to-one,  but when you think about the POST – ViewModel from client to Controller does not need to have the Primary key. And on PUT you don’t want the created by overwritten with any thing. You get my point.

If you want to keep the destination value on map you need to initialse mapping like this.

 CreateMap<QuestionUpdateViewModel, Question>()
                    .ForMember(dest => dest.QuestionId, opt => opt.UseDestinationValue())
                    .ForMember(dest => dest.CreatedBy, opt => opt.UseDestinationValue())
                    .ForMember(dest => dest.CreatedOn, opt => opt.UseDestinationValue());

So in your PUT can be like this

 [HttpPut("{id}")]
        public IActionResult Update(int id, [FromBody]QuestionUpdateViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var entity = _repository.GetById(id);

            if (entity != null)
            {
                Mapper.Map(model, entity);
                _repository.Update(entity);
            }
            else
            {
                return NotFound();
            }

            var output = Mapper.Map<QuestionDetailsViewModel>(entity);

            return CreatedAtRoute("GetQuestion", new { controller = "Questions", id = output.QuestionId }, output);
        }

Post can be like this

        [HttpPost]
        public IActionResult Create([FromBody]QuestionViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var entity = Mapper.Map<Question>(model);
            _repository.Add(entity);

            var output = Mapper.Map<QuestionDetailsViewModel>(entity);

            return CreatedAtRoute("GetQuestion", new { controller = "Questions", id = output.QuestionId }, output);
        }

 

Leave a comment