Entity Framework Code First: how to map multiple self-referencing many-to-many relationships

做~自己de王妃 提交于 2019-11-28 01:05:45

By adding this in the DbContext.OnModelCreating method:

UPDATE Added table-naming map according to nameEqualsPNamePrubeGoldberg's comment above:

modelBuilder.Entity<Person>().HasMany(x => x.Brothers).WithMany()
    .Map(x => x.ToTable("Person_Brothers"));
modelBuilder.Entity<Person>().HasMany(x => x.Sisters).WithMany()
    .Map(x => x.ToTable("Person_Sisters"));

I got this unit test to pass

[TestMethod]
public void TestPersons()
{
    var brother = new Person() { Name = "Brother 1", Age = 10 };
    var sister = new Person() { Name = "Sister 1", Age = 12 };
    var sibling = new Person() { Name = "Sibling 1", Age = 18 };
    sibling.Brothers.Add(brother);
    sibling.Sisters.Add(sister);

    using (var db = new MyDatabase())
    {
        db.Persons.Add(brother);
        db.Persons.Add(sister);
        db.Persons.Add(sibling);

        db.SaveChanges();
    }

    using (var db = new MyDatabase())
    {
        var person = db.Persons
            .Include(x => x.Sisters)
            .Include(x => x.Brothers)
            .FirstOrDefault(x => x.Name.Equals(sibling.Name));

        Assert.IsNotNull(person, "No person");
        Assert.IsTrue(person.Brothers.Count == 1, "No brothers!");
        Assert.IsTrue(person.Sisters.Count == 1, "No sisters");
    }
}

That also creates the link tables you're talking about.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!