Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Self-referencing many-to-many recursive relationship code first Entity Framework

I can't seem to make this work at all

class Member {     public virtual IList<Member> Friends { get; set; }     [Key]     public int MemberId { get; set; }     public string Name{ get; set; } } 

I tried adding Mappings but in vain. Is there a way to do so with CTP5?

like image 774
Korayem Avatar asked Feb 26 '11 04:02

Korayem


People also ask

How do you establish a self referencing many-to-many relationship?

A self-referencing many-to-many relationship exists when a given record in the table can be related to one or more other records within the table and one or more records can themselves be related to the given record.

How does Entity Framework handle many-to-many relationships in core?

Many-to-many relationships require a collection navigation property on both sides. They will be discovered by convention like other types of relationships. The way this relationship is implemented in the database is by a join table that contains foreign keys to both Post and Tag .

What is many-to-many relationships in code first approach?

A many-to-many relationship is defined in code by the inclusion of collection properties in each of the entities - The Categories property in the Book class, and the Books property in the Category class: public class Book. { public int BookId { get; set; }


1 Answers

By convention, Code First will take uni-directional associations as one to many. Therefore you need to use fluent API to let Code First know that you want to have a many to many self referencing association:

protected override void OnModelCreating(ModelBuilder modelBuilder) {     modelBuilder.Entity<Member>().HasMany(m => m.Friends).WithMany().Map(m =>         {             m.MapLeftKey("MemberId");             m.MapRightKey("FriendId");             m.ToTable("MembersFriends");         }     ); } 
like image 194
Morteza Manavi Avatar answered Sep 23 '22 05:09

Morteza Manavi