title: Adding and updating entities with Entity Framework
body: <p>In my last project I have used Entity Framework 5 Code First. I completed my project but had a lot of pain during the development process.</p>
  
  <p>I tried to explain my pain below:</p>
  
  <p>I had several data classes in my data access logic layer like Product, ProductCategory, Order, Company, Manufacturer etc... Each class has some references to some other classes. For example, a Product instance has a ProductCategory property. </p>
  
  <p>Inside Add and Update methods of my Data Access Object classes I set the states of each property (other than the primitive types) to Unchanged or Modified in the context. Below is some part of an update method of some dao class:</p>
  
  <pre><code>context.Entry(entity).State = System.Data.EntityState.Modified;
  if (entity.Category != null)
      context.Entry(entity.Category).State = System.Data.EntityState.Unchanged;
  
  if (entity.Manufacturer != null)
      context.Entry(entity.Manufacturer).State = System.Data.EntityState.Unchanged;
  
  foreach (var specificationDefinition in entity.SpecificationDefinitions)
  {
      context.Entry(specificationDefinition).State = System.Data.EntityState.Unchanged;
      foreach (var specificationValue in specificationDefinition.Values)
      {
          context.Entry(specificationValue).State = System.Data.EntityState.Unchanged;
      }
  }
  </code></pre>
  
  <p>This code goes like this. Some of my add or update methods are about 30 lines of code. I think I am doing something wrong, adding or updating an entity should not be this much pain but when I don't set the states of the objects I either get exception or duplicate entries in the database. Do I really have to set the state of each property that maps to database?</p>