Validate Deletion of Related Records MVC Entity Framework

0

I am new to MVC, I want to know how I can validate that at the moment of deleting a parent record I am shown a message that tells the user that it can not be deleted because of the relationship with the child records.

I have a validation in the create POST of my controller which is the following:

 public ActionResult Create([Bind(Include = "AreaId,NameArea")] Area area)
    {
        if (db.Area.Any(a => a.NameArea == area.NameArea))
        {
            ModelState.AddModelError("NameArea", "Ya existe una Área con este nombre.");
        }

        if (ModelState.IsValid)
        {
            db.Area.Add(area);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(area);
    }

I would like to validate the deletion similar to the previous one, or if there were any other way I would appreciate it.

    
asked by SELSO ALONSO 05.12.2018 в 03:52
source

2 answers

0

You can add the validation when you delete since you pass the id of the entity

public ActionResult Delete(int id) {

    var area = db.Area.Include(x=>x.PropRelacionada)
                        .FirstOrDefault(x=> x.Id == id);

    if(area == null)
    {
        ModelState.AddModelError("IdArea", "No existe una Área con el ID.");
    }

    if(area.PropRelacionada.Count() > 0)
    {
        ModelState.AddModelError("xxArea", "El Area se encuentra relacionado con XX");
    }

     return View();
}

The idea is that if you use entity framework maps the relationship between the entities, so with the Include() you can recover if you have a relationship with the entity you want to validate

Upload Related Entities

    
answered by 05.12.2018 в 04:41
0

I found the solution for this problem turns out that I had to validate the SaveChanges () with try and catch:

    // POST: Areas/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public ActionResult DeleteConfirmed(int id)
    {
        Area area = db.Area.Find(id);
        db.Area.Remove(area);

        try
        {
            db.SaveChanges();
        }
        catch (Exception ex)
        {
            if (ex.InnerException != null &&
               ex.InnerException.InnerException != null &&
               ex.InnerException.InnerException.Message.Contains("REFERENCE"))
            {
                ModelState.AddModelError(string.Empty, "El registro no puede borrarse porque tiene otros registros relacionados.");
            }
            else
            {
                ModelState.AddModelError(string.Empty, ex.Message);
            }

            return View(area);
        }


        return RedirectToAction("Index");
    }

Then in the Delete view add:

@Html.ValidationSummary(true, "", new { @class = "text-danger" })

In this way, the relationships between parent and child records are valid.

    
answered by 06.12.2018 в 02:44