Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>In terms of entities (or objects) you have a <code>Class</code> object which has a collection of <code>Students</code> and a <code>Student</code> object that has a collection of <code>Classes</code>. Since your <code>StudentClass</code> table only contains the Ids and no extra information, EF does not generate an entity for the joining table. That is the correct behaviour and that's what you expect.</p> <p>Now, when doing inserts or updates, try to think in terms of objects. E.g. if you want to insert a class with two students, create the <code>Class</code> object, the <code>Student</code> objects, add the students to the class <code>Students</code> collection add the <code>Class</code> object to the context and call <code>SaveChanges</code>:</p> <pre><code>using (var context = new YourContext()) { var mathClass = new Class { Name = "Math" }; mathClass.Students.Add(new Student { Name = "Alice" }); mathClass.Students.Add(new Student { Name = "Bob" }); context.AddToClasses(mathClass); context.SaveChanges(); } </code></pre> <p>This will create an entry in the <code>Class</code> table, two entries in the <code>Student</code> table and two entries in the <code>StudentClass</code> table linking them together.</p> <p>You basically do the same for updates. Just fetch the data, modify the graph by adding and removing objects from collections, call <code>SaveChanges</code>. Check <a href="https://stackoverflow.com/questions/3612477/entity-framework-4-many-to-many-update/3622599#3622599">this similar question</a> for details.</p> <p><strong>Edit</strong>:</p> <p>According to your comment, you need to insert a new <code>Class</code> and add two existing <code>Students</code> to it:</p> <pre><code>using (var context = new YourContext()) { var mathClass= new Class { Name = "Math" }; Student student1 = context.Students.FirstOrDefault(s =&gt; s.Name == "Alice"); Student student2 = context.Students.FirstOrDefault(s =&gt; s.Name == "Bob"); mathClass.Students.Add(student1); mathClass.Students.Add(student2); context.AddToClasses(mathClass); context.SaveChanges(); } </code></pre> <p>Since both students are already in the database, they won't be inserted, but since they are now in the <code>Students</code> collection of the <code>Class</code>, two entries will be inserted into the <code>StudentClass</code> table.</p>
 

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