且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

实体框架代码优先:如何映射多个自引用多对多关系

更新时间:2022-11-05 09:17:38

通过在DbContext.OnModelCreating方法中添加它:

By adding this in the DbContext.OnModelCreating method:

更新根据上面的nameEqualsPNamePrubeGoldberg的评论添加了表命名映射:

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

我通过了这个单元测试

[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.