Using automapper to update entities with relationships

asp.net-core automapper c# entity-framework-core

Question

I'm using EF Core and Automapper to update my entities. I have an entity called "Aluno", which has a relationship to "Endereco". Here is the code:

public class Aluno : ApplicationUser{

    ...
    public Endereco Endereco { get; set; }
    ...
}

public class AlunoViewModel : UserViewModel
{
    public int Id { get; set; }

    public EnderecoViewModel Endereco { get; set; }
}

public class Endereco{

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get;set; }

   ...
}

public class EnderecoViewModel {

    public int Id { get;set; }
    ...
}

The automapper configuration:

config.CreateMap<Aluno, AlunoViewModel>().ReverseMap();
config.CreateMap<Endereco, EnderecoViewModel>().ReverseMap();

AlunosController:

[HttpPut]
    public JsonResult Put([FromBody]AlunoViewModel vm)
    {
        if (ModelState.IsValid)
        {
            var aluno = _context.Alunos
                .Single(o => o.Id == vm.Id);

            Mapper.Map(vm, aluno);

            _context.SaveChanges();

            Response.StatusCode = (int)System.Net.HttpStatusCode.OK;
            return Json(true);
        }

        Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
        return Json(false);
    }

When I try to update an "Aluno" entity, I'm getting an exception on context.SaveChanges():

Cannot insert explicit value for identity column in table 'Enderecos' when IDENTITY_INSERT is set to OFF.

But i'm not trying to insert a new "Endereco", just update the entity "Aluno", and maybe update the "Endereco", which is loaded correctly inside the var aluno.

Am I doing something wrong?

1
1
12/13/2016 2:35:11 PM

Accepted Answer

Try the following syntax:

Mapper
    .CreateMap<Aluno, AlunoViewModel>()
    .ForMember(
        dest => dest.Endereco,
        opt => opt.MapFrom(src => src.EnderecoViewModel)
    );
3
12/13/2016 9:13:22 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow