ASP.NET MVC删除按钮

时间:2018-08-30 18:48:02

标签: sql-server asp.net-mvc

单击删除按钮时,出现此错误。

  

SqlException:DELETE语句与REFERENCE约束“ FK_Reserva_Quarto”冲突。在数据库“GestãoHotel”的表“ dbo.Reserva”的“ ID_Quarto”列中发生了冲突。

有人知道原因吗?

IMAGE

控制器:

// GET: Quartos/Delete/5
public ActionResult Delete(int? id)
{
      if (id == null)
      {
          return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
      }

      Quarto quarto = db.Quarto.Find(id);

      if (quarto == null)
      {
           return HttpNotFound();
      }

      return View(quarto);
}

// POST: Quartos/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
     Quarto quarto = db.Quarto.Find(id);
     db.Quarto.Remove(quarto);
     db.SaveChanges();
     return RedirectToAction("Index");
}

查看:

<div class="table-responsive panel">
 <table class="table">
  <tbody>
     <tr>
        <td class="text-success"><i class="fa fa-list-ol"></i> Nº Quarto</td>
        <td>@Model.ID_Quarto</td>
      </tr>
      <tr>
        <td class="text-success"><i class="fa fa-bed"></i> Tipo de Quarto</td>
        <td>@Model.TipoQuarto</td>
      </tr>
    </tbody>
   </table>
</div>

<table class="table">
 <tbody>
  <tr>
     @using (Html.BeginForm())
     {
     @Html.AntiForgeryToken()
     <td class="text-center">
      <button type="submit" class="btn btn-danger btn-circle btn-xl" data-toggle="tooltip" title="Eliminar"> <i class="glyphicon glyphicon-ok"></i></button>
 <button type="button" onclick="location.href='@Url.Action("Index", "Quartos")'" class="btn btn-primary btn-circle btn-xl" data-toggle="tooltip" title="Voltar"><i class="glyphicon glyphicon-arrow-left"></i></button>
     </td>
      }
    </tr>
   </tbody>
 </table>

连接字符串:

<connectionStrings>
    <add name="Hotel" 
         connectionString="Data Source=DESKTOP-BC284NS\SQLEXPRESS;initial catalog=GestãoHotel;integrated security=True;" 
         providerName="System.Data.EntityClient" />
    <add name="HotelEntities" 
         connectionString="metadata=res://*/Models.BaseDados.GestãoHotel.csdl|res://*/Models.BaseDados.GestãoHotel.ssdl|res://*/Models.BaseDados.GestãoHotel.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=DESKTOP-BC284NS\SQLEXPRESS;initial catalog=GestãoHotel;integrated security=True;App=EntityFramework&quot;" 
         providerName="System.Data.EntityClient" />
</connectionStrings>

2 个答案:

答案 0 :(得分:1)

您必须先删除Reservas,然后才能删除Quarto,如下所示:

[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
     List<Reserva> Reservas = db.Reserva.Where(r => r.ID_Quarto == id).ToList();
     db.Reserva.RemoveRange(Reservas);

     Quarto quarto = db.Quarto.Find(id);
     db.Quarto.Remove(quarto);
     db.SaveChanges();
     return RedirectToAction("Index");
}

此外,作为永久解决方案,请在DbContext中添加以下配置,然后运行迁移并相应地更新数据库:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
     base.OnModelCreating(modelBuilder);

     modelBuilder.Entity<Reserva>().HasRequired(j => j.Quarto)
                                   .WithMany(c => c.Reservas)
                                   .HasForeignKey(j => j.ID_Quarto).WillCascadeOnDelete(true);
}

希望您的问题得到解决!

答案 1 :(得分:0)

我认为您对此有选择。  -选项1:使用ON DELETE CASCADE  -选项2:按正确顺序删除。这意味着您应该先从Reserva中删除行,然后再从Quarto中删除行。

您可以关注此示例。希望对您有帮助,我的朋友:))

//选项1:

ALTER TABLE <child_table> WITH CHECK 
ADD CONSTRAINT <fk_name> FOREIGN KEY(<column(s)>)
REFERENCES <parent_table> (<column(s)>)
ON DELETE CASCADE

选项2:

// POST: Quartos/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            //Delete the rows from Reserva first
            var reservaObj = db.Reserva.Where(t => t.ID_Quarto == id).ToList();
            db.Reserva.RemoveRange(reservaObj);

            Quarto quarto = db.Quarto.Find(id);
            db.Quarto.Remove(quarto);
            db.SaveChanges();
            return RedirectToAction("Index");
        }