代码之家  ›  专栏  ›  技术社区  ›  Sayed M. Idrees

实体框架-与父类具有相同类的类列表

  •  0
  • Sayed M. Idrees  · 技术社区  · 3 年前

    我有一个用户的父类,它有如下关注者列表。

    public class User
    { 
        public User()
        { 
            Followers = new HashSet<Follower>(); 
        }
        [Key]
        public int ID { get; set; }
    
        [Required]
        public string username { get; set; }
          
        public virtual ICollection<Follower> Followers { get; set; }
    }
    

    Follower类有其他用户跟随父用户。 这样地

    public class Follower
    {
        [Key]
        public int ID { get; set; }
    
        [Required]
        public virtual User user { get; set; }
    }
    

    但当我向用户表中的列表中添加对象时,

    parentUser.Followers.Add(new Follower { user = childUser});
    //The parentClass is object of User class
    

    一切看起来都很好,但当编译器通过 _myDb.SaveChanges();

    我检查了数据库,它有以下值。

    +----+--------+
    | ID | UserID |
    +====+========+
    | 1  | 1      |
    +----+--------+
    
    0 回复  |  直到 3 年前
        1
  •  0
  •   mostafa khoramnia    3 年前

    如果我理解正确,你需要2用户和追随者之间的关系

    一个用于指定每个关注者的父用户,一个用于指定每个关注者的确切用户(childUser),对吗?

    编辑:

    根据你的回答,我认为这有助于你: 我想这是你的答案:

    public class User
    {
        public int Id { get; set; }
        public string Name { get; set; }
    
        public ICollection<Follow> Followers { get; set; }//followers of this user
        public ICollection<Follow> Followings { get; set; }//users that followed by this user
    }
    public class Follow
    {
        public int Id { get; set; }
        public int FollowerUserId { get; set; }//who
        public User FollowerUser { get; set; }
        public int FollowingUserId { get; set; }//followed who
        public User FollowingUser { get; set; }
    }
    

    在OnModelCreating中:

    modelBuilder.Entity<User>().HasMany(x => x.Followers).WithOne(y => y.FollowingUser).HasForeignKey(y => y.FollowingUserId);
    modelBuilder.Entity<User>().HasMany(x => x.Followings).WithOne(y => y.FollowerUser).HasForeignKey(y => y.FollowerUserId);