【问题标题】:How to Update database table row when the foreign key has the same value ASP.NET mvc外键具有相同值时如何更新数据库表行ASP.NET mvc
【发布时间】:2017-08-20 06:16:04
【问题描述】:

我有一个应用程序,商店可以在其中完成问卷调查。在这个应用程序中,我有两个表 db.StoreAud(pk:AuditId) 包含所有商店信息,以及 db.storequests(pk:ReviewId) 包含所有问题信息。

AuditId 是 db.storequests 表中的外键。现在这是一个问题,如果商店完成调查问卷,数据完美保存在数据库中,但是同一个商店再次执行调查问卷,db.storequests 在数据库中创建一个具有新主键值的新行,而不是更新前一个排。问题是如果同一家商店再次进行相同的问卷调查,我如何更新前一行。希望从那时起。

db.StoreAUD

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Key]
    [Column(Order = 1)]
    public int AuditId { get; set; }

    public string Date { get; set; }

    public int StoreNumber { get; set; }
    public string StoreName { get; set; }

db.storequests

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Key]
    public int ReviewId { get; set; }

    public int AuditId { get; set; }

    public int QuestionOne { get; set; }

    public string QuestionTwo { get; set; }
    public string QuestionThree { get; set; }
    public string QuestionFour { get; set; }

控制器

   [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(StoreQuestions storequestions) 
    {
        if (ModelState.IsValid)
        {
            StoreAudit findingAudit = db.StoreAudit.Find(storequestions.AuditId); // grabbing the id from th store audit table
            findingAudit.ReadOnlyTickBox = true;
            db.StoreQuestions.Add(storequestions);
            db.SaveChanges();
            return RedirectToAction("Details", "Audit", new { id = storequestions.AuditId });
        }

        return View(storequestions);
    }

【问题讨论】:

  • 与您对 StoreAudit 执行此操作的方式相同。您首先查找它,如果存在,则更新返回的行。仅在不存在时添加。
  • 使用Update() 操作进行更新。
  • i@ErikFunkenbusch 我想我有,但没有成功,你能否发布一些代码以防万一你不介意我犯了一些错误
  • @mxmissile 可能会发布一些示例代码
  • @cedPound - 你觉得你是怎么做到的?无论如何,您每次都将提交的 StoreQuestions 添加到您的db.StoreQuestions。您根本不需要查找 StoreQuestions。

标签: entity-framework asp.net-mvc-4 sql-update insert-update


【解决方案1】:

我会将您的更新逻辑分离成一个新的Update 操作,遵循Single Responsibility Principle

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Update(StoreQuestions storequestions) 
    {
         if (ModelState.IsValid)
         {
              StoreAudit findingAudit = db.StoreAudit.Find(storequestions.AuditId);
              findingAudit.ReadOnlyTickBox = true;

              // update objects here

              db.SaveChanges();
              return RedirectToAction("Details", "Audit", new { id = storequestions.AuditId });
              }

            return View(storequestions);
         }
     }

【讨论】:

  • 我仍然需要更新对象,因为我仍然不确定如何去做
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-04
  • 2020-02-22
  • 2018-01-28
  • 2021-11-29
  • 1970-01-01
  • 2021-10-12
相关资源
最近更新 更多