Many-to-many relationship between entities of same type in MVC3

前端 未结 1 1864
名媛妹妹
名媛妹妹 2020-12-30 16:55

I have an ASP.NET MVC3 application, where I use Entity Framework 4.3 Code-First and Migrations.

I\'ve been trying to create a many-to-many relationship between entit

相关标签:
1条回答
  • 2020-12-30 17:43

    Since It is a Many to Many Self Joined relationship, User entity should have a Followers and Following properties both of Type User. So Let us alter your class to include those

    public class User
    {
        public int ID { get; set; }
        public string Name { get; set; }       
        public virtual ICollection<User> Followers { get; set; }
        public virtual ICollection<User> Following { get; set; }
    }
    

    Now update the DbContext class to have a Property which returns the Users

     public DbSet<User> Users { set; get; }
    

    We need to tell EntityFramework that we need to have a many to many relations ship between these two. So Let us do that with Fluent API by overriding OnModelCreating method

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<User>().HasMany(m => m.Followers).WithMany(p => p.Following).Map(w => w.ToTable("User_Follow").MapLeftKey("UserId").MapRightKey("FollowerID"));
        base.OnModelCreating(modelBuilder);
    }
    

    Now Entity Framework will create the tables like this.

    enter image description here

    Note that we explicitly told Entity Framework to use UserId and FollowerId as the Forign Key column name. If we havent mentioned that, EF will use User_ID and User_ID1 as the column names.

    0 讨论(0)
提交回复
热议问题