Nickolay Kabash
Nickolay Kabash

Reputation: 239

EF self one-to-many relationship

I want to implement one-to-many relationship with EF6. Table User can handle many Friends, i can implement that with map table:

--TABLE USERS:
Id

--TABLE USER_MAP:
UserOwnerId
UserFriendId

But how to implement that with EF6?

Here is my entity User:

public class User
{
    ...
    public virtual List<User> Friends { get; set; }
    ...
}

Upvotes: 0

Views: 731

Answers (3)

Bassam Alugili
Bassam Alugili

Reputation: 17033

you can defined in Code first like that:

1) Fluent API:

public class Student
{
    public Student() { }

    public int StudentId { get; set; }
    public string StudentName { get; set; }

    public virtual Standard Standard { get; set; }
}

public class Standard
{
    public Standard()
    {
        Students = new List<Student>();
    }
    public int StandardId { get; set; }
    public string Description { get; set; }

    public virtual ICollection<Student> Students { get; set; }
}

Fleut Api: in your DbContext:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
        //one-to-many 
        modelBuilder.Entity<Student>()
                    .HasRequired<Standard>(s => s.Standard) 
                    .WithMany(s => s.Students);

}

virtual keyword is only for Lazy loading you can remove it if you do not need it

2) Code first:

public class Student
{
    public Student()
    {
        Students= new List<Student>();
    }

    public int StundendId{ get; set; }

    public string StudentName { get; set; }

    public int? SharedStudentId{ get; set; }

    [ForeignKey("SharedStudentId")]
    public Student SharedStudent{ get; set; }

    public virtual ICollection<Student> SharedStudents{ get; set; }
}

Upvotes: 0

Badruzzaman
Badruzzaman

Reputation: 41

One-to-Many relationship using DataAnnotations:

  public class User
    {
        public User() { }

        public int UserId { get; set; }
        public string Name { get; set; }

        public virtual Friends friends { get; set; }
    }

    public class Friends
    {
        public Friends()
        {
            Users = new List<User>();
        }
        public int FriendId { get; set; }
        public string Name { get; set; }

        public virtual ICollection<User> Users { get; set; }
    }

Upvotes: 1

Samrat Alamgir
Samrat Alamgir

Reputation: 362

You can use something like this

// Relationships

HasRequired(t => t.User)
            .WithMany(t => t.Friends)
            .HasForeignKey(d => d.UserId);

https://msdn.microsoft.com/en-us/data/hh134698.aspx

Upvotes: 1

Related Questions