title: Duplicates when adding entity to child collection of another entity. Thanks to overridden Equals?
body: <pre><code>public class Foo
  {
      public int Id { get; set; }
      public ICollection&lt;Bar&gt; Bars{get;set;}
  }
  
  public class Bar
  {
      public int Id { get; set; }
      public int FooId { get; set; }
  
      public override bool Equals(object obj)
      {
          var bar= obj as Bar;
          return bar != null &amp;&amp;
                 Id == bar.Id;
      }
  
      public override int GetHashCode()
      {
          return 2108858624 + Id.GetHashCode();
      }
  }
  
  public class SomeClass
  {
      DbContext _context = ...; // injected via DI
  
      public void AddNewBarToFoo(int fooId)
      {
          // Option 1
          // result: foo.Bars contains two items
          Foo foo = _context.Foos
                 .Where(f =&gt; f.id == fooId)
                 .Include(f =&gt; f.Bars)
                 .FirstOrDefault();
          foo.Bars.Add(new Bar());
          _context.SaveChanges();
  
          // Option 2
          // result: foo.Bars contains one item
          Bar bar = new Bar();
          bar.FooId = FooId;
          _context.Bars.Add(bar);
          _context.SaveChanges();
  
          // Option 3:
          // Remove _context.SaveChanges() from Option 1
  
          // Option 4:
          // Remove the Id comparison from Bar.Equals()
      }
  }
  </code></pre>
  
  <p>Today I noticed something weird using Entity Framework Core. In the <code>AddNewBarToFoo</code> method of <code>SomeClass</code> I want to add a new Bar to a collection of Foos. Originally I used Option 1, but I noticed that, after the call to <code>SaveChanges</code>, foo.Bars would contain the new Bar twice.<br>
  I noticed that removing the call to <code>SaveChanges</code> would not add the second Bar and still persist the Bar correctly. Using Option 2 works as expected too.</p>
  
  <p>I found this quite strange behavior and upon investigating a little I found that the reason for this is that I overrode the <code>Equals</code> method of Bar and that I used the Id to check for equality.<br>
  Removing the Id comparison from the <code>Equals</code> method and otherwise using Option 1 works as expected: Foo.Bars contains the new Bar only once.  </p>
  
  <p>I actually have two questions now:  </p>
  
  <ol>
  <li><p>What is the reason Entity Framework adds the same Bar twice?<br>
  I suppose it adds the new Bar to the context once, giving it an Id and then encounters it again (somehow?) but this instance still has Id 0 and thus is considered different than the first per my <code>Equals</code> method.  </p></li>
  <li><p>Was I wrong to use the Id in my overridden <code>Equals</code> method? Or in the code for adding a new Bar to a Foo? Is it bad practice to override <code>Equals</code>?<br>
  In short: what is the 'correct' way to do what I tried to do?</p></li>
  </ol>