title: Adding record duplicates other object using entity framework
body: <p>I am trying to add a new record in an MVC controller method using Entity framework.
  When i just used "InsertOrUpdate" the audittype got duplicated. Based on the answer from <a href="https://stackoverflow.com/questions/12637602/entity-framework-adding-record-with-a-related-object">Entity Framework adding record with a related object </a> i hoped to fix it pretty qiock. This is the code I have right now:</p>
  
  <p>Controller:</p>
  
  <pre><code>if (ModelState.IsValid)
  {
      Audit newAudit = Factory.GetNew();
      newAudit.Name = model.Name;
      newAudit.Deadline = model.Deadline;
      newAudit.AuditType = auditTypeRepository.Find(model.SelectedAuditTypeId);
  
      Repository.InsertOrUpdate(newAudit);
      Repository.Save();
  
      return RedirectToAction(MVC.Audits.Details(newAudit.Id)); 
  }
  </code></pre>
  
  <p>Repository:</p>
  
  <pre><code>public override void InsertOrUpdate(Qdsa.WebApplications.AuditMaster.Data.Audit model)
  {
      if (model.Id == default(int))
      {
          // New entity
          context.Audits.Add(model);
      }
      else
      {
          // Existing entity
          model.ModifiedOn = DateTime.Now;
          context.Entry(model).State = EntityState.Modified;
      }
      //If I leave out the code below the AuditType will be duplicated
      if (model.AuditType != null)
      {
          context.Entry&lt;AuditType&gt;(model.AuditType).State = EntityState.Unchanged;
      }
  }
  
  public virtual void Save()
  {
      context.SaveChanges();
  }
  </code></pre>
  
  <p>So i thought I fixed the problem. However, AuditType has Child objects too. And now these childobjects get duplicated.
  What is the right way to add entities with child objects which already exists?
  Because the AuditType is required I can't save it without first and then update it. any suggestions?</p>
  
  <p>UPDATE:
  Both the AuditRepostory and the AuditTypeRepository inherit from BaseRepository which has the context as:</p>
  
  <pre><code>protected DBContext context = new DBContext ();
  
  public virtual T Find(int id)
  {
      return All.SingleOrDefault(s =&gt; s.Id == id);
  }
  </code></pre>