title: How to save combined (new+modified) detached entities in Entity Framework?
body: <p>What is the proper and fast way to save combined new and modified detached POCO entities?</p>
  
  <p>I was thinking about these methods:</p>
  
  <pre><code>    private void Method_2(IList&lt;Entity&gt; entities) //detached entities
      {
          //This method is using SELECT to check if entity exist
          using (var context = new ModelContainer())
          {
              foreach (Entity entity in entities)
              {
                  var foundEntity = context.CreateObjectSet&lt;Entity&gt;().SingleOrDefault(t =&gt; t.Id == entity.Id);
                  context.Detach(foundEntity);    //Remove it from ObjectStateManager
  
                  if (foundEntity != null)//It is modified entity
                  {
                      context.AttachTo("EntitySet", entity); //Attach our entity
                      context.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified); //We know it exists
                  }
                  else//It is new entity
                  {
                      context.CreateObjectSet&lt;Entity&gt;().AddObject(entity);
                  }
              }
              context.SaveChanges();
          }
      }
  
      private void Method_1(IList&lt;Entity&gt; entities) //detached entities
      {
          //This method doesn't select anything from DB, but i have ta call Savechanges after each object
          using (var context = new ModelContainer())
          {
              foreach (Entity entity in entities)
              {
                  try
                  {
                      context.AttachTo("EntitySet", entity);
                      context.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);
                      context.SaveChanges();
                  }
                  catch (OptimisticConcurrencyException)
                  {
                      context.ObjectStateManager.ChangeObjectState(entity, EntityState.Added);
                      context.SaveChanges();
                  }
              }
          }
      }
  </code></pre>
  
  <blockquote>
    <p>When you are working in detached environment you have to know which entity was added and which is modified - it is your responsibility to keep this information and provide it to ObjectContext.</p>
  </blockquote>
  
  <p>Well i agree with this statement if you found yourself in situation when you need to use EF code like this in EF definitely something is wrong with you decision. I have chosen wrong tool for this job.</p>