First, create a self-referential many-to-many recursive connection code. Framework for Entities

c# code-first entity-framework many-to-many

Question

This is not working for me at all.

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

Ineffectively, I attempted to add Mappings. Is it possible to achieve it using CTP5?

1
42
10/9/2012 10:49:44 AM

Accepted Answer

Code First will often interpret unidirectional relationships as one to many. Because of this, you must utilize Fluent API to inform Code First that you want 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");
        }
    );
}
63
2/4/2020 6:20:15 PM

Popular Answer

If I'm right, you may use the following code to change the name of the many-to-many table:

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");
        }
    );
}

Hope this is useful.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow