【问题标题】:Using Entity Framework, how do I add a record to the mapping table in a Many to Many relationship使用实体框架,如何在多对多关系中向映射表添加记录
【发布时间】:2010-08-10 05:01:20
【问题描述】:

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

呼叫

身份证 来电者姓名 来电时间

类别

身份证 类别名称

呼叫类别

呼叫ID 类别ID

当我在实体框架中对这些进行建模时,映射表“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 的一些东西上。 :-/

非常感谢任何帮助!

响应 gnome....

我认为您在这里有所作为。虽然,我不会叫“添加”(或者是附加)吗?喜欢:

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

【问题讨论】:

  • 你最后想到了什么?还是你决定了什么?

标签: entity-framework entity-framework-4


【解决方案1】:

我认为需要添加类别模型,而不仅仅是添加 id。试试看,

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

【讨论】:

  • 查看我在原始问题中的回复。我无法在此评论中使用“代码”,而且它的评论格式很糟糕。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多