代码之家  ›  专栏  ›  技术社区  ›  Shayne

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

  •  5
  • Shayne  · 技术社区  · 14 年前

    我有以下表格(为了可读性而压缩):

    呼叫

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

    类别

    身份证件 类型名

    调用类别

    卡里德 分类ID

    当我在实体框架中对这些进行建模时,映射talbe“callcategories”被省略了。我在如何通过英孚将记录添加到这个表上感到困惑。

    我已经走了这么远了:

    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;
            }
        }
    }
    

    我是使用“添加”还是“附加”。而且,我似乎是在犯错误。我真的应该创建一个新类别吗?当我真的想向多对多映射表中添加一条记录时,这似乎会在类别表中创建一条实际记录。

    我只是不能把我的大脑包在这些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(); 
    
    1 回复  |  直到 14 年前
        1
  •  2
  •   gnome    14 年前

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

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