【问题标题】:How to save an ID from a table to another table in ASP.NET MVC?如何在 ASP.NET MVC 中将一个表中的 ID 保存到另一个表中?
【发布时间】:2019-10-20 03:58:55
【问题描述】:

我在将“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 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();
   }
}

【问题讨论】:

  • 您遇到了什么问题或错误?
  • @abhinavpratap 在“tb_parkingslots”中添加“slot_name”时,“slot_id”会加一。同时,我想将 'slot_id' 和 'slot_name' 保存在 'tb_freeeslot' 中。问题是“slot_id”无法保存在“tb_freeslot”中。保存“slot_name”没有问题
  • tb_parkingslots 完成后Save changesid 自动设置请调试您的代码
  • 尝试使用此行addi.slot_id = add["slot_id"] 而不是您当前拥有的行。另外,我会敦促您使用更具描述性和更直观的变量名称 - add 用于 tb_parkingslot 类型的变量既危险(因为 add 是一个常用的表达式),而且信息量不大 - 使用像 parkingSlot 这样真正表达你正在处理的内容的东西
  • @marc_s 怎么可能用 [ ] 索引到 tb_parkingslots 类型的表达式

标签: c# sql-server asp.net-mvc database


【解决方案1】:

当您将数据保存在 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();

【讨论】:

  • 值被传递,当我调试时。但它没有显示在 db 表中。即,在 tb_freeslot 中
  • 是的,它有效。表格有问题并解决了
猜你喜欢
  • 2022-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-29
相关资源
最近更新 更多