Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Entity Framework, how do I add a record to the mapping table in a Many to Many relationship

I have the following tables (condensed for readability):

Call

ID CallerName CallerTime

Categories

ID CategoryName

CallCategories

CallID CategoryID

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.

I have gotten 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 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.

I just can't seem to wrap my brain around some of this EF stuff. :-/

Any help is MUCH appreciated!

In response to gnome....

I think you are onto something here. Although, wouldn't I call "Add" (or is it Attach)? Like:

//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(); 
like image 528
Shayne Avatar asked Nov 05 '22 10:11

Shayne


1 Answers

I believe need to add the category model, not just add the id. try,

//Add the Category to the Call
call.Categories = context.Categories.FirstOrDefault(c => c.categoryId == categoryId);
context.SaveChanges();
like image 62
gnome Avatar answered Dec 12 '22 18:12

gnome