title: C# Entity Framework "An entity object cannot be referenced by multiple instances of IEntityChangeTracker"
body: <p>This error is thrown a lot, but I can't find the solution. I am new to the Entity Framework and in my first approach I got this error.</p>
  
  <p>This is what I have. I have a company class and a branch class. Both classes have their own repository. A company has one Branch, while one branch can have multiple companies.</p>
  
  <p>In my GUI I fill a combo with Branch objects, which I get from my BranchRepository:</p>
  
  <pre><code>    public IList&lt;Branch&gt; GetAllBranches()
      {
          var query = _context.Branches;
  
          IList&lt;Branch&gt; branches = query.ToList();
  
          return branches;
      }
  </code></pre>
  
  <p>This is result is the datasource of the branch combobox.</p>
  
  <p>When I want to save the company, I do something like this:</p>
  
  <pre><code>company.VisitorAddress = txtVisitAddress.Text;
  company.City = txtCity.Text;
  company.CompanyName = txtCompany.Text;
  company.PhoneNumber = txtPhoneNumber.Text;
  company.ZipCode = txtZipcode.Text;
  company.Branch = ((Branch)cmbBranches.SelectedItem);
  company.Website = txtWebsite.Text;
  </code></pre>
  
  <p>Then, I call my company repository to save my company. Here is what the save method looks like:</p>
  
  <pre><code>public bool Save(Company company)
  {
      _context.AddToCompanies(company);   // &lt;-- This is where the error is thrown.
      _context.SaveChanges();
  
      return true;
  }
  </code></pre>
  
  <p>When the save method is invoked, I get the error 'An entity object cannot be referenced by multiple instances of IEntityChangeTracker'. </p>
  
  <p>Clearly I'm doing something wrong, but what?</p>