title: Saving AutoMapper mapped Collections of Entities using Entity Framework
body: <p>I have the following Entity Framework Entities:</p>
  
  <pre><code>public class Region
  {
      public int RegionId { get; set; } // Primary Key
      public string Name { get; set; }
      public virtual ICollection&lt;Country&gt; Countries { get; set; } // Link Table
  }
  public class Country
  {
      public int CountryId { get; set; } // Primary Key
      public string Name { get; set; }
      public int RegionId { get; set; } // Foreign Key
  }
  </code></pre>
  
  <p>I map these using AutoMapper to the following ViewModels:</p>
  
  <pre><code>public class RegionViewModel
  {
      public int RegionId { get; set; }
      public string Name { get; set; }
      public virtual ICollection&lt;int&gt; Countries { get; set; }
  }
  public class CountryViewModel
  {
      public int CountryId { get; set; }
      public string Name { get; set; }
  }
  </code></pre>
  
  <p>I want to translate my ViewModels to Entities using AutoMapper so I can save a new Region. This is my mapping code:</p>
  
  <pre><code>Mapper.CreateMap&lt;RegionViewModel, Region&gt;()
      .ForMember(x =&gt; x.Countries, x =&gt; x.MapFrom(y =&gt; y.Countries.Select(z =&gt; new Country() { CountryId = z }).ToArray()));
  </code></pre>
  
  <p>This causes an exception when adding the region in the repository as it also tries to create a new instance of Country with a null Name. One solution is to change the <code>Add</code> method in my repository to set the State of the country objects to Unchanged.</p>
  
  <pre><code>public async Task Add(Region region)
  {
      foreach (Country country in region.Countries)
      {
          this.Context.Entry(country).State = EntityState.Unchanged;
      }
      await base.Add(region);
  }
  </code></pre>
  
  <p>The other alternative solution is to use more complicated translation logic which uses another repository to get the real country objects. This approach has slower performance because it has to make an extra call to the database but you also get a more complete Region object.</p>
  
  <pre><code>Mapper.CreateMap&lt;RegionViewModel, Region&gt;();
  Mapper.CreateMap&lt;int[], Country[]&gt;().ConvertUsing(x =&gt; countryRepository.GetAll().Result.Where(y =&gt; x.Contains(y.CountryId)).ToArray());
  </code></pre>
  
  <p>I lean to the first one but what is the correct approach?</p>