Delete table record with composite key

0

I'm starting to use EntityFramework and MVC in C # .NET, and I have a problem trying to delete a record from a table that uses a composite key.

Driver:

// GET: DocenteCursoes/Delete/5
    public ActionResult Delete(string curso, string docente)
    {
        if (curso == null && docente == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        DocenteCurso docenteCurso = db.DocenteCurso.Find(curso, docente);
        if (docenteCurso == null)
        {
            return HttpNotFound();
        }
        return View(docenteCurso);
    }

    // POST: DocenteCursoes/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public ActionResult DeleteConfirmed(string curso, string docente)
    {
        DocenteCurso docenteCurso = db.DocenteCurso.Find(curso, docente);
        db.DocenteCurso.Remove(docenteCurso);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }

Model:

[Table("DocenteCurso")]
public partial class DocenteCurso
{
    [Key]
    [Column(Order = 0)]
    [StringLength(50)]
    public string Curso { get; set; }

    [Key]
    [Column(Order = 1)]
    [StringLength(50)]
    public string Docente { get; set; }
}

Vista:

<div>
<h4>DocenteCurso</h4>
<hr />
<dl class="dl-horizontal">
</dl>

@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()

    <div class="form-actions no-color">
        <input type="submit" value="Delete" class="btn btn-default" /> |
        @Html.ActionLink("Back to List", "Index")
    </div>
}

I do not have problems with a primary key but with a composite key I do not know how to do it, any suggestions?

    
asked by Luis Acuña 13.03.2018 в 21:18
source

2 answers

0

I understand that you want to delete from a table and that it is related, because to pass the two fields if it is from the Teaching Table, you only pass the id of that teacher and then use a transaction to eliminate the courses, or otherwise send the id of the course and eliminate teachers; this way you make sure you have consistent information in the database. I use the following code, in which I return a "succes" if they were really deleted.

In the ActionResult method.

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

        var prov = db.MtoProveedores.Find(id);

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


        var response = DBProvee.Delete(prov, User.Identity.Name);

        if (response.succeeded)
        {
            return Json(new { success = response.succeeded, }, JsonRequestBehavior.AllowGet); 
            //return Json(new { success = response.succeeded });
        }

        return View(prov);
    }

and a class

 public static Response Delete(MtoProveedor view, string UserName)
    {
         var user = db.MtoUsuarios.Where(u => u.UserName == UserName).FirstOrDefault();
        var date = DateTime.Now;

        using (var Transaccion = db.Database.BeginTransaction())
        {
            try
            {
                /*===============================================================
                  ELIMINAR INVERSIONISTAS
                ===============================================================*/

                var inv = db.MtoInversionistas.Where(d => d.MtoProveedorId == view.MtoProveedorId);
                foreach (var Details in inv)
                {
                    db.MtoInversionistas.Remove(Details);
                }

                db.SaveChanges();

                /*===============================================================
                  ELIMINAR REPRESENTACIONES LEGALES
                ===============================================================*/
                var replegal = db.MtoRepLegales.Where(d => d.MtoProveedorId == view.MtoProveedorId);
                foreach (var Details in replegal)
                {
                    db.MtoRepLegales.Remove(Details);
                }

                db.SaveChanges();

                /*===============================================================
                  ELIMINAR PROVEEDOR DEFINITIVAMENTE
                ===============================================================*/
                var proveedor = db.MtoProveedores.Find(view.MtoProveedorId);

                db.MtoProveedores.Remove(proveedor);

                db.SaveChanges();

                Transaccion.Commit();

                return new Response { succeeded = true };                    
            }
            catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
            {
                Exception raise = dbEx;
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        string message = string.Format("{0}:{1}",
                            validationErrors.Entry.Entity.ToString(),
                            validationError.ErrorMessage);

                        raise = new InvalidOperationException(message, raise);
                    }
                }
                return new Response { succeeded = false, Message = raise.Message };
            }

        }

    }
    
answered by 14.03.2018 в 16:14
0

in principle you do not have to do anything special. The only thing missing in your view are the inputs that carry the values of the primary key. Simply adding: @Html.HiddenFor(model=>model.Curso) and @Html.HiddenFor(model=>model.Docente) in the Post you will already receive the 2 values and with that it is enough to locate the instance to be deleted, as you have the method.

    
answered by 15.03.2018 в 13:08