1

我正在創建我的DB using EF CodeFirst如何在使用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

我花了很多時間來嘗試這個。

有什麼辦法可以達到同樣的效果嗎?

回答

1

下面的代碼解決了我的problem-

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; } 
} 

我只是added-

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

謝謝!大家...

相關問題