Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing Entity Framework, how do I add a record to the mapping table in a Many to Many relationship
    primarykey
    data
    text
    <p>I have the following tables (condensed for readability):</p> <h2>Call</h2> <p>ID CallerName CallerTime</p> <h2>Categories</h2> <p>ID CategoryName</p> <h2>CallCategories</h2> <p>CallID CategoryID</p> <p>When I modeled these in the Entity Framework the mapping talbe "CallCategories" was left out. I am stumped on how to get a record added to this table via the EF.</p> <p>I have gotten this far:</p> <pre><code>public void AddCategory(int callID, int categoryID) { using (var context = new CSMSEntities()) { try { //Get the Call var call = context.Calls.FirstOrDefault(x =&gt; x.callID == callID); //Create a new Category Category category = new Category(); category.categoryID = categoryID; //Add the Category to the Call call.Categories.Add(category); context.SaveChanges(); } catch (Exception ex) { throw ex; } } } </code></pre> <p>Do I use "Add" or "Attach". Also, it seems like I may be approaching this wrong. Should I actually be creating a new Category? It seems like that would create an actual record in the Category table, when I really want to just add a record to the many-to-many mapping table.</p> <p>I just can't seem to wrap my brain around some of this EF stuff. :-/</p> <p>Any help is MUCH appreciated!</p> <p>In response to gnome....</p> <p>I think you are onto something here. Although, wouldn't I call "Add" (or is it Attach)? Like:</p> <pre><code>//Get the Call var call = context.Calls.FirstOrDefault(x =&gt; x.callID == callID); //Find the Category and Add to the Call Category category = context.Categories.FirstOrDefault(c =&gt; c.categoryID == categoryID); call.Categories.Add(category); context.SaveChanges(); </code></pre>
    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.
 

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