title: Using automapper to update entities with relationships
body: <p>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:</p>
  
  <pre><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; }
      ...
  }
  </code></pre>
  
  <p>The automapper configuration:</p>
  
  <pre><code>config.CreateMap&lt;Aluno, AlunoViewModel&gt;().ReverseMap();
  config.CreateMap&lt;Endereco, EnderecoViewModel&gt;().ReverseMap();
  </code></pre>
  
  <p>AlunosController:</p>
  
  <pre><code>[HttpPut]
      public JsonResult Put([FromBody]AlunoViewModel vm)
      {
          if (ModelState.IsValid)
          {
              var aluno = _context.Alunos
                  .Single(o =&gt; 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);
      }
  </code></pre>
  
  <p>When I try to update an "Aluno" entity, I'm getting an exception on context.SaveChanges():</p>
  
  <blockquote>
    <p>Cannot insert explicit value for identity column in table 'Enderecos'
    when IDENTITY_INSERT is set to OFF.</p>
  </blockquote>
  
  <p>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.</p>
  
  <p>Am I doing something wrong?</p>