title: EF - Saving a new entity with linked existing entities creating duplicates
body: <pre><code>public class Car {
      public string SomeProperty { get; set; }
      public Manufacturer Manufacturer { get; set; }
      public IList&lt;Color&gt; Colors { get; set; }
  }
  
  public class Manufacturer { 
      public int Id { get; set; }
      public string Name { get; set; }
  }
  
  public class Color { 
      public int Id { get; set; }
      public string Name { get; set; }
  }
  </code></pre>
  
  <p>I already have tables full of Colors and Manufacturers. When I create a new car I want to be able to assign it a Color and Manufacturer bound from .net MVC.</p>
  
  <p>When I save my new car with </p>
  
  <pre><code>context.Cars.Add(car);
  </code></pre>
  
  <p>A new Car is created (great) but a new Color and Manufacturer are also created even though these objects already had an Id and Name set that matched the content in the database.</p>
  
  <p>The two solutions I see are to either write a custom save method for car, and tell the context that the Manufacturer and Color are Unchanged.</p>
  
  <pre><code>context.Cars.Add(car);
  context.Entry(car.Manufacturer).State = EntityState.Unchanged;
  foreach (Color color in car.Colors)
     context.Entry(car.Color).State = EntityState.Unchanged;
  </code></pre>
  
  <p>Alternatively, to load the Manufacturer and Color from EF and then link them to the Car, instead of using the MVC bound objects.</p>
  
  <pre><code>car.Manufacturer = carRepository.GetManufacturer(car.Manufacturer.Id);
  car.Colors = carRepository.GetColorsById(car.Colors);
  </code></pre>
  
  <p>I am not thrilled by either solution as this example is very trivial, but my real cases are far more complicated. I don't really want to have to fiddle around with EF in detail for each object I save. I have lots of complex object graphs to save and this seems very error prone.</p>
  
  <p>Is there a way of making EF behave more like NHibernate, whereby you can give it something with an ID already assigned and it will assume without your intervention that it already exists?</p>
  
  <p>Edit - question clarified to show collection of existing entities as well as many-to-one relationships.</p>