小编Sha*_*yne的帖子

使用实体框架,如何在多对多关系中向映射表添加记录

我有以下表格(为了便于阅读而精简):

呼叫

ID CallerName CallerTime

分类

ID CategoryName

CallCategories

CallID CategoryID

当我在实体框架中对这些进行建模时,省略了映射塔"CallCategories".我很难理解如何通过EF将记录添加到此表中.

我已经走到这一步了:

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我使用"添加"还是"附加".而且,似乎我可能正在接近这个错误.我真的应该创建一个新类别吗?当我真的想在多对多映射表中添加记录时,似乎会在Category表中创建一个实际记录.

我似乎无法将我的大脑包裹在这些EF的东西中.: - /

任何帮助深表感谢!

响应gnome ....

我想你在这里做点什么.虽然,我不会称之为"添加"(或者它是附加)吗?喜欢:

//Get the …
Run Code Online (Sandbox Code Playgroud)

entity-framework entity-framework-4

5
推荐指数
1
解决办法
2217
查看次数