开发者

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开发者_如何学Go.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(); 


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();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜