Thursday, January 31, 2013

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


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


//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();
}
//Note: There is a known bug in CTP5 that won't let you customize the join table column
//names in this scenario.

1 comment:

  1. Hello sir ,

    Thanks for your help , could you please tell me how to add columns to the auto generated table ??

    ReplyDelete