entity-framework - 使用 Entity Framework ,如何在多对多关系中向映射表添加记录

标签 entity-framework entity-framework-4

我有以下表格(为了可读性而精简):

称呼

ID
来电者姓名
来电时间

类别

ID
分类名称

调用类别

来电显示
类别ID

当我在 Entity Framework 中对这些进行建模时,映射表“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;
        }
    }
}

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

我似乎无法将我的大脑围绕在一些 EF 的东西上。 :-/

任何帮助深表感谢!

回应侏儒....

我认为你在这里有所作为。虽然,我不会叫“添加”(或者是附加)?喜欢:
//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(); 

最佳答案

我相信需要添加类别模型,而不仅仅是添加 id。尝试,

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

关于entity-framework - 使用 Entity Framework ,如何在多对多关系中向映射表添加记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3443933/

相关文章:

c# - Entity Framework 错误 : An object with a null EntityKey value cannot be attached to an object context

c# - 搜索实体的所有字段

c# - 在 Entity Framework Core 中保存 HashSet<string>

c# - 使用 ASP.NET async/await 进行线程管理

c# - 集合上的动态 LINQ?

entity-framework-4 - EF 4.1 Code First - 我应该使用什么模式?

c# - EF4.1 + MARS - 更新时不允许新事务

c# - 如何: Avoid Inserting Related Entities?

linq - 如何拦截 IQueryProvider 查询的结果(单个结果除外)

c# - 找不到我的 Entity Framework 数据库