title: How do I update an entity with nested entities with AutoMapper and save the updated Entity with Entity Framework?
body: <p>I've created a mapping to map a collection in the ViewModel to another collection on a Model which seems to work without a problem. After mapping, The child object of the Model has the appropriate updates.</p>
  
  <pre><code>configuration.CreateMap&lt;SourceViewModel, Destination&gt;()                
              .ForMember(d =&gt; d.ChildOfDestination, 
                        opt =&gt; opt.MapFrom(s =&gt; Mapper.Map&lt;ICollection&lt;SourceViewModel&gt;, ICollection&lt;Destination&gt;&gt;(s.ChildOfSource)));
  </code></pre>
  
  <p>However, on save an error is thrown:</p>
  
  <blockquote>
    <p>The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.</p>
  </blockquote>
  
  <p>What I have found is ChangeTracker.Entries() has extra items with a state of "Added". For example, my Model.ChildCollection has a count of 2, but in Entries(), I have the original 2 items from ChildCollection with states of "Modified", and 2 of the same items with States of "Added"</p>
  
  <pre><code>public async Task&lt;IHttpActionResult&gt; Update([FromBody] SourceViewModel viewModel) {
      var model = await _repository.GetByIdAsync(viewModel.Id);
      Mapper.Map(viewModel, model);
      _repository.Update(model);
      await _unitOfWork.SaveAsync();
  }
  </code></pre>
  
  <p>I wrote some code to get around the problem for the time being but it's a hack to a bigger problem that I'm not sure how to solve.</p>
  
  <pre><code>foreach (var child in ViewModel.Child)
  {
    var record = Model.Child.SingleOrDefault(c =&gt; c.ID == child.ID);
  
    if (record != null)
        Mapper.Map(child, record);
    else
        Model.Child.Add(Mapper.Map&lt;SourceViewModel, Destination&gt;(child));
  }
  </code></pre>