在EntityFramework Core中自引用多对多关系

时间:2017-11-23 14:46:55

标签: c# ef-core-2.0

尝试定义自引用多对多关系:

AppContext.cs:

$('td:has(button)').text()

UserRelationship.cs:

modelBuilder.Entity<User>().ToTable("user").HasKey(u => u.Id);
modelBuilder.Entity<User>().Property(u => u.Id).HasColumnName("id");

modelBuilder.Entity<UserRelationship>().ToTable("user_relationship").HasKey(us => us.Id);
modelBuilder.Entity<UserRelationship>().Property(us => us.Id).HasColumnName("id");
modelBuilder.Entity<UserRelationship>().Property(us => us.SubordinateId).HasColumnName("subordinate_id");
modelBuilder.Entity<UserRelationship>().Property(us => us.SuperiorId).HasColumnName("superior_id");
modelBuilder.Entity<UserRelationship>().HasOne(us => us.Subordinate).WithMany(u => u.SubordinateRelationships).HasForeignKey(us => us.SubordinateId).OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity<UserRelationship>().HasOne(us => us.Superior).WithMany(u => u.SuperiorRelationships).HasForeignKey(us => us.SuperiorId).OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity<UserRelationship>().HasIndex(us => us.SubordinateId);
modelBuilder.Entity<UserRelationship>().HasIndex(us => us.SuperiorId);

假设我添加了这样的关系{user.id ='1'和subordinate.id ='2'}

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 => _subordinate; }
    public int SubordinateId { get => _subordinateId; }
    public User Superior { get => _superior; }
    public int SuperiorId { get => _superiorId; }

    #region Persistence-related members

    protected UserRelationship() {

    }

    #endregion
}

到目前为止一切顺利,我得到了:user.SubordinateRelationships [0] = {subordinateId ='2',superiorId ='1'}

user.SubordinateRelationships.Add(new UserRelationship(subordinate, user));

保存后,关系出错了,我得到了:user.SubordinateRelationships [0] = {user.id ='1'和subordinate.id ='1'}

用户ID与下属ID相同。我做错了什么?

0 个答案:

没有答案