我想将值插入到我正在使用实体框架和 linq 的多对多关系表中。我想建立插入查询(.net Framework 4)
以下是表格
菜单 - menu_id、menu_name、menu_desc
迎合 - cater_id、cater_name、enable_ind
关系表 Menu_Cater - menu_id、cater_id
如果有实现此插入和删除的简单方法,我尝试过几种情况似乎不起作用
我想将值插入到我正在使用实体框架和 linq 的多对多关系表中。我想建立插入查询(.net Framework 4)
以下是表格
菜单 - menu_id、menu_name、menu_desc
迎合 - cater_id、cater_name、enable_ind
关系表 Menu_Cater - menu_id、cater_id
如果有实现此插入和删除的简单方法,我尝试过几种情况似乎不起作用
我不知道,如果你现在需要它,但我会告诉你怎么做。如果我没听错的话,你的意思就是那样。
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 的工作
假设您有Menu
andCater
对象(来自下拉列表或但是),只需:
Menu_Cater
记录如下所示:
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()
取决于数据上下文的类型。