Entity Framework Code First: How to map multiple relationships between many with many

I created an object type that has several collection properties that reference elements of the same type. In other words, it reflects a single database table in which rows are randomly grouped so that a row can be displayed in multiple groups.

In the following simplified example, the Person class has Brothers and Sisters collection properties that also reference Person objects:

 public class Person { public Person() { Brothers = new Collection<Person>(); Sisters = new Collection<Person>(); } [Key] public string Name { get; set; } public int Age { get; set; } public virtual ICollection<Person> Brothers { get; set; } public virtual ICollection<Person> Sisters { get; set; } } 

The Entity Framework seems to consider this a valid model, but interprets it to create a single PersonPersons join table that does not reflect the brother-sister relationship.

I suppose the solution is to use the free API to explicitly map individual join tables for two relationships, but despite extensive experimentation, I was not able to get this to work.

Any suggestions please?

Thanks Tim

+8
entity-framework many-to-many code-first self-reference
source share
1 answer

By adding this to the DbContext.OnModelCreating method:

UPDATE Added a table of naming names according to the comment nameEqualsPNamePrubeGoldberg 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"); } } 

It also creates the link tables you are talking about.

+8
source share

All Articles