插入&删除多对多关系表中的值

时间:2012-10-16 16:27:11

标签: asp.net linq entity-framework

我想在多对多关系表中插入值 我正在使用实体框架& LINQ。我想建立插入查询(.net Framework 4)

以下是表格

菜单 -     menu_id,     MENU_NAME,     menu_desc

Cater - cater_id,            cater_name,            enable_ind

关系表 Menu_Cater - menu_id,                     cater_id

我试过几个案例似乎不起作用, 如果有一种简单的方法来实现这个插入&删除

2 个答案:

答案 0 :(得分:0)

假设您拥有MenuCater个对象(或者从下拉列表中删除),只需:

  1. 创建Menu_Cater记录
  2. 将其设置为在提交时插入
  3. 提交更改
  4. 以下展示:

    <强> VB.NET

    Dim menu As Menu = GetSelectedMenu() ' However you get the Menu record
    Dim cater As Cater = GetSelectedCater() ' However you get the Cater record
    
    Dim relationship = New Menu_Cater()
    ' EITHER:
    relationship.menu_id = menu.menu_id
    relationship.cater_id = cater.cater_id
    ' OR:
    ' relationship.menu = menu
    ' relationship.cater = cater
    
    Using db = new MyDataContext
        db.Menu_Cater.InsertOnSubmit( relationship )
        db.SubmitChanges()
    End Using
    

    <强> C#

    Menu menu = GetSelectedMenu(); // However you get the Menu record
    Cater cater = GetSelectedCater(); // However you get the Cater record
    
    Menu_Cater relationship = new Menu_Cater();
    // EITHER:
    relationship.menu_id = menu.menu_id;
    relationship.cater_id = cater.cater_id;
    // OR:
    // relationship.menu = menu
    // relationship.cater = cater
    
    using (db = new MyDataContext()) {
        db.Menu_Cater.InsertOnSubmit(relationship);
        db.SubmitChanges();
    }
    

    可能需要对变量/数据库字段名称进行小的更改。可能db.Save()而不是db.SubmitChanges(),具体取决于数据上下文的类型。

答案 1 :(得分:0)

我不知道,如果你现在需要它,但我会展示如何做到这一点。 如果我理解得对,你的意思就是这样。

public ActionResult Create(Cater cater, int menuId)
{
    //Find menu with our menu_id
    Menu menu = db.Menus.Where(m => m.menu_id == menuId).FirstOrDefault();

    //Add cater for this Menu
    menu.Cater.Add(cater);
    db.SaveChanges();

    return somethere...
}

public ActionResult Remove(int caterId, int menuId)
{
 //Choose menu, from him we will delete cater which we need 
 Menu menu = db.Menus.Where(m => m.menu_id == menuId).FirstOrDefault();

 //Find cater which we want delete from this Menu
 Cater cater = menu.Cater.Where(c => c.cater_id == caterId).FirstOrDefault();

 //Remove him from Table Menu_Cater
 menu.Cater.Remove(cater);
 db.SaveChanges();

 return somethere...
}

多数民众赞成。它适用于MVC4