我有以下表格(为了可读性而精简):
称呼
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/