如何使用EF CodeFirst在用户类中添加用户列表



我正在创建我的DB using EF CodeFirst

我创建了以下用户类-

 public class User
    {
        public User()
        {
        }
        [Key]
        public int ID { get; set; }
        [Required, MinLength(4), MaxLength(20)]
        public string Name { get; set; }
        [Required, MinLength(8), MaxLength(40)]
        public string Email { get; set; }
        [Required, MinLength(8), MaxLength(15)]
        public string Password { get; set; }
        [Required]
        public DateTime JoinedOn { get; set; }
        public List<Users> Friends { get; set; } // Problem Adding List of Users in User Class
    }

我想存储List of friends for each user。而且,我无法将Friends collection属性添加到此User Class

我花了很多时间尝试这个。

有什么方法可以做到这一点吗?

下面的代码解决了我的问题-

public class User
{
    public User()
    {
        Users = new List<User>();
        Friends = new List<User>();
        ChatRooms = new List<ChatRoom>();
    }
    [Key]
    public int ID { get; set; }
    [Required, MinLength(4), MaxLength(20)]
    public string Name { get; set; }
    [Required, MinLength(8), MaxLength(40)]
    public string Email { get; set; }
    [Required, MinLength(8), MaxLength(15)]
    public string Password { get; set; }
    [Required]
    public DateTime JoinedOn { get; set; }
    [InverseProperty("Friends")]
    public virtual ICollection<User> Users { get; set; }
    public virtual ICollection<User> Friends { get; set; }
    [InverseProperty("Participants")]
    public virtual ICollection<ChatRoom> ChatRooms { get; set; }
}

我刚刚添加了-

[InverseProperty("Friends")]
public virtual ICollection<User> Users { get; set; }
public virtual ICollection<User> Friends { get; set; }

谢谢!每个人

最新更新