C# 如何在ASP.NET MVC中将一个ID从一个表保存到另一个表?
我在将'slot_id'(自动递增主键)从C# 如何在ASP.NET MVC中将一个ID从一个表保存到另一个表?,c#,sql-server,asp.net-mvc,database,C#,Sql Server,Asp.net Mvc,Database,我在将'slot_id'(自动递增主键)从tb_parkingslots传递到tb_freeslot并保存时遇到问题 这是我的密码: 控制器: // GET: Admin/Create public ActionResult Addspace() { return View(); } // POST: Admin/Create [HttpPost] public ActionResult Addspace(FormCollection collection) { try
tb_parkingslots
传递到tb_freeslot
并保存时遇到问题
这是我的密码:
控制器:
// GET: Admin/Create
public ActionResult Addspace()
{
return View();
}
// POST: Admin/Create
[HttpPost]
public ActionResult Addspace(FormCollection collection)
{
try
{
tb_parkingslots add = new tb_parkingslots();
add.slot_name = collection["name"];
db.tb_parkingslots.Add(add);
int i = db.SaveChanges();
if (i > 0)
{
tb_freeslot addi = new tb_freeslot();
addi.slot_id = Convert.ToInt32(collection["id"]); //which is auto increment - primary key in tb_parkingslots
addi.slot_name = collection["name"];
db.tb_freeslot.Add(addi);
db.SaveChanges();
ViewBag.s = "success";
return View();
}
else
{
ViewBag.f = "failed";
return View();
}
}
catch
{
return View();
}
}
在tb_parkingslots表中保存数据时。EF将自动填充对象的Id属性
tb_parkingslots add = new tb_parkingslots();
add.slot_name = collection["name"];
db.tb_parkingslots.Add(add);
int i = db.SaveChanges(); // Here you will get the ID.
然后可以使用此ID将数据保存在tb_freeslot表中
tb_freeslot addi = new tb_freeslot();
addi.slot_id = add.id; //which is slot ID when you saved data in tb_parkingslots
addi.slot_name = collection["name"];
db.tb_freeslot.Add(addi);
db.SaveChanges();
您遇到了什么问题或错误?@abhinavpratap在“tb\u parkingslots”中添加“slot\u name”时,“slot\u id”将增加1。同时,我想将“slot\u id”和“slot\u name”保存在“tb\u freeeslot”中。问题是“slot\u id”无法保存在“tb\u freeslot”中。保存“slot\u name”
tb\u parkingslots
一旦完成保存更改
classid
自动设置,请调试代码尝试使用此行addi.slot\u id=add[“slot\u id”]
。此外,我敦促您使用更具描述性和更直观的变量名称-add
对于类型为tb_parkingslot
的变量,这两种名称都是危险的(因为add
是一种常用的表达式),而且信息量也不是很高——使用像parkingSlot
这样的东西来真正表达你正在处理的事情with@marc_s当我调试时,如何可能通过[]将索引传递到tb_parkingslotsvalue类型的表达式。但在db表中没有显示。也就是说,在tb_Freeslot中,它是有效的。表有问题并解决了它