Using the Entity Framework, how to add an entry to the mapping table from many to many relationships

I have the following tables (compressed for readability):

Call

ID CallerName CallerTime

Category

ID CategoryName

Callcategories

CallID CategoryID

When I modeled them in the Entity Framework, the talbe "CallCategories" display was omitted. I do not understand how to get the record added to this table through EF.

I got this far:

public void AddCategory(int callID, int categoryID) { using (var context = new CSMSEntities()) { try { //Get the Call var call = context.Calls.FirstOrDefault(x => 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; } } } 

Do I use Add or Attach. Also, it looks like I might get this wrong. Should I create a new category? It seems like this would create the actual entry in the Category table when I really want to just add the entry to the many-to-many mapping table.

I just can't believe my brain covers some of these EF materials.: - /

Any help is much appreciated!

In response to gnome ....

I think you are up to something here. Although, can I call "Add" (or is it attached)? How:

 //Get the Call var call = context.Calls.FirstOrDefault(x => x.callID == callID); //Find the Category and Add to the Call Category category = context.Categories.FirstOrDefault(c => c.categoryID == categoryID); call.Categories.Add(category); context.SaveChanges(); 
+6
entity-framework entity-framework-4
source share
1 answer

It seems to me that you need to add a category model, and not just add an id. try

 //Add the Category to the Call call.Categories = context.Categories.FirstOrDefault(c => c.categoryId == categoryId); context.SaveChanges(); 
+3
source share

All Articles