title: Self-referencing many-to-many relationships in EntityFramework Core
body: <p>Trying to define a self-referencing many-to-many relationship:</p>
  
  <p>AppContext.cs:</p>
  
  <pre><code>modelBuilder.Entity&lt;User&gt;().ToTable("user").HasKey(u =&gt; u.Id);
  modelBuilder.Entity&lt;User&gt;().Property(u =&gt; u.Id).HasColumnName("id");
  
  modelBuilder.Entity&lt;UserRelationship&gt;().ToTable("user_relationship").HasKey(us =&gt; us.Id);
  modelBuilder.Entity&lt;UserRelationship&gt;().Property(us =&gt; us.Id).HasColumnName("id");
  modelBuilder.Entity&lt;UserRelationship&gt;().Property(us =&gt; us.SubordinateId).HasColumnName("subordinate_id");
  modelBuilder.Entity&lt;UserRelationship&gt;().Property(us =&gt; us.SuperiorId).HasColumnName("superior_id");
  modelBuilder.Entity&lt;UserRelationship&gt;().HasOne(us =&gt; us.Subordinate).WithMany(u =&gt; u.SubordinateRelationships).HasForeignKey(us =&gt; us.SubordinateId).OnDelete(DeleteBehavior.Cascade);
  modelBuilder.Entity&lt;UserRelationship&gt;().HasOne(us =&gt; us.Superior).WithMany(u =&gt; u.SuperiorRelationships).HasForeignKey(us =&gt; us.SuperiorId).OnDelete(DeleteBehavior.Cascade);
  modelBuilder.Entity&lt;UserRelationship&gt;().HasIndex(us =&gt; us.SubordinateId);
  modelBuilder.Entity&lt;UserRelationship&gt;().HasIndex(us =&gt; us.SuperiorId);
  </code></pre>
  
  <p>UserRelationship.cs:</p>
  
  <pre><code>public class UserRelationship : DomainObject
  {
      private User _subordinate;
      private int _subordinateId;
      private User _superior;
      private int _superiorId;
  
      public UserRelationship(User subordinate, User superior) {
          _subordinate = subordinate;
          _subordinateId = subordinate.Id;
          _superior = superior;
          _superiorId = superior.Id;
      }
  
      public User Subordinate { get =&gt; _subordinate; }
      public int SubordinateId { get =&gt; _subordinateId; }
      public User Superior { get =&gt; _superior; }
      public int SuperiorId { get =&gt; _superiorId; }
  
      #region Persistence-related members
  
      protected UserRelationship() {
  
      }
  
      #endregion
  }
  </code></pre>
  
  <p>Let's say I add a relationship like this {user.id = '1' and subordinate.id = '2'}</p>
  
  <pre><code>user.SubordinateRelationships.Add(new UserRelationship(subordinate, user));
  </code></pre>
  
  <p>So far so good, here I got: user.SubordinateRelationships[0] = {subordinateId = '2', superiorId = '1'}</p>
  
  <pre><code>_dbContext.Users.Update(user);
  _dbContext.SaveChanges();
  </code></pre>
  
  <p>After saving, the relationship has gone wrong, here I got: user.SubordinateRelationships[0] = {user.id = '1' and subordinate.id = '1'}</p>
  
  <p>User id is the same ad the subordinate id. What I am doing wrong?</p>