Note that there are some explanatory texts on larger screens.

plurals
  1. POEntity Framework many-to-many not populating collections
    primarykey
    data
    text
    <p>I have two POCO classes, each containing a collection of the other. I am attempting to configure a many-to-many relationship between these classes. However, when I load the context, EF does not populate any of the collections of each object. How can this be done automatically?</p> <pre><code>public class POCO1 { public int ID { get; set; } public virtual ICollection&lt;POCO2&gt; POCO2s { get; set; } } public class PCOO2 { public int ID { get; set; } public virtual ICollection&lt;POCO1&gt; POCO1s { get; set; } } public class POCOContext : DbContext { public DbSet&lt;POCO1&gt; POCO1s { get; set; } public DbSet&lt;POCO2&gt; POCO2s { get; set; } modelBuilder.Entity&lt;POCO1&gt;() .HasKey(p =&gt; p.ID); modelBuilder.Entity&lt;POCO1&gt;() .HasMany(p =&gt; p.POCO2s).WithMany(p =&gt; p.POCO1s); modelBuilder.Entity&lt;POCO2&gt;() .HasKey(p =&gt; p.ID); modelBuilder.Entity&lt;POCO2&gt;() .HasMany(p =&gt; p.POCO1s).WithMany(p =&gt; p.POCO2s); } public class Test { static void Main(string[] args) { using (var context = new POCOContext()) { context.Database.Initialize(true); var p1 = context.POCO1s.Create(); var p2 = context.POCO2s.Create(); p1.POCO2s.Add(p2); p2.POCO1s.Add(p1); context.saveChanges(); } // reload context from db using (var context = new POCOContext()) { context.POCO1s.ToList()[0].POCO2s.Count(); // == 0, but should be 1 context.POCO2s.ToList()[0].POCO1s.Count(); // == 0, but should be 1 } } } </code></pre> <p>Edit to include more info: from what I have read it should not be necessary to include annotations or even specify keys using Fluent API, and using these conventions EF 5.0 should configure the relations correctly. Indeed this appears to be the case, because the database tables are constructed correctly using code first (there is a POCO1 table, a POCO2 table, and an intersection table, all of which are populated correctly during testing). The problem is when reading the data back out, it does not seem to populate the many to many relationships. Other posts on SO and various tutorials and MSDN documentation suggest that using the proper conventions, lazy loading, and virtual collections should work, but that is not the behavior I'm seeing.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload