title: EF & Automapper. Update nested collections
body: <p>I trying to update nested collection (Cities) of Country entity.</p>
  
  <p>Just simple enitities and dto's:</p>
  
  <pre><code>// EF Models
  public class Country
  {
      public int Id { get; set; }
      public string Name { get; set; }
      public virtual ICollection&lt;City&gt; Cities { get; set; }
  }
  
  public class City
  {
      public int Id { get; set; }
      public string Name { get; set; }
      public int CountryId { get; set; }
      public int? Population { get; set; }
  
      public virtual Country Country { get; set; }
  }
  
  // DTo's
  public class CountryData : IDTO
  {
      public int Id { get; set; }
      public string Name { get; set; }
      public virtual ICollection&lt;CityData&gt; Cities { get; set; }
  }
  
  public class CityData : IDTO
  {
      public int Id { get; set; }
      public string Name { get; set; }
      public int CountryId { get; set; }
      public int? Population { get; set; }
  }
  </code></pre>
  
  <p>And code itself (tested in console app for the sake of simplicity):</p>
  
  <pre><code>        using (var context = new Context())
          {
              // getting entity from db, reflect it to dto
              var countryDTO = context.Countries.FirstOrDefault(x =&gt; x.Id == 1).ToDTO&lt;CountryData&gt;();
  
              // add new city to dto 
              countryDTO.Cities.Add(new CityData 
                                        { 
                                            CountryId = countryDTO.Id, 
                                            Name = "new city", 
                                            Population = 100000 
                                        });
  
              // change existing city name
              countryDTO.Cities.FirstOrDefault(x =&gt; x.Id == 4).Name = "another name";
  
              // retrieving original entity from db
              var country = context.Countries.FirstOrDefault(x =&gt; x.Id == 1);
  
              // mapping 
              AutoMapper.Mapper.Map(countryDTO, country);
  
              // save and expecting ef to recognize changes
              context.SaveChanges();
          }
  </code></pre>
  
  <p>This code throws exception:</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>even though entity after last mapping seems just fine and reflects all changes properly.</p>
  
  <p>I've spent much time finding solution but got no result. Please help.</p>