Asp.net Mvc Delete Button
When I click the delete button, I get this error. SqlException: The DELETE statement conflicted with the REFERENCE constraint 'FK_Reserva_Quarto'. The conflict occurred in databas
Solution 1:
You have to delete Reservas
first before deleting the Quarto
as follows:
[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");
}
Moreover for permanent solution, add the following configuration in DbContext
then run a migration and update the database accordingly:
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);
}
Hope your problem will be solved!
Solution 2:
I think you have options for this. - Option 1: Use ON DELETE CASCADE - Option 2: Deleting In Correct Order. It means that you should delete the rows from Reserva first, then the rows from Quarto.
You can follow this sample. Hope to help, my friend :))
//Option 1:
ALTERTABLE<child_table>WITHCHECKADDCONSTRAINT<fk_name>FOREIGN KEY(<column(s)>)
REFERENCES<parent_table> (<column(s)>)
ONDELETE CASCADE
OPTION 2:
// POST: Quartos/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
//Delete the rows from Reserva firstvar 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");
}
Post a Comment for "Asp.net Mvc Delete Button"