Ankit Goel
Ankit Goel

Reputation: 353

How to add a List of Users in a User Class using EF CodeFirst

I'm creating my DB using EF CodeFirst.

I have created the following User Class-

 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
    }

I want to store the List of friends for each user. And, I'm unable to add a Friends collection property to this User Class.

I have spent a lot of time trying this.

Is there any way to achieve the same?

Upvotes: 1

Views: 907

Answers (1)

Ankit Goel
Ankit Goel

Reputation: 353

The following code solved my 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; }
}

I just added-

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

Thanks! Everyone...

Upvotes: 1

Related Questions