我正在尝试删除另一个表中引用的对象。
我想删除的对象:
[Table("Local")]
public class Local
{
[Key]
public int Id { get; set; }
public string ViejoId { get; set; }
[Required]
[Index("UniqueNuevoId", 1, IsUnique = true)]
[Display(Name ="Nuevo Id")]
public int NuevoId { get; set; }
[Display(Name ="Id Unificado")]
public string UnificadoCon { get; set; }
[Required(ErrorMessage = "Es necesario agregar el nombre del comercio")]
[Display(Name = "Comercio")]
public string NombreComercio { get; set; }
[Display(Name = "Nom Unificado")]
public string NombreComercioUnificado { get; set; }
[Required]
public string Direccion { get; set; }
[Required]
[Display(Name ="Tel")]
public string Telefono { get; set; }
[Required]
public string Provincia { get; set; }
[Required]
public string Localidad { get; set; }
public Proveedor Proveedor { get; set; }
public Estado Estado { get; set; }
public DateTime FechaIngreso = DateTime.Today;
public bool Bonificado { get; set; }
public bool Premium { get; set; }
[Display(Name ="Instalación")]
[DataType(DataType.Date)]
public DateTime FechaInstalacion { get; set; }
public virtual List<NotasAdjuntas> notas { get; set; }
相关的对象
[Table("NotasAdjuntas")]
public class NotasAdjuntas
{
public int Id { get; set; }
[Required]
[MinLength(3)]
[MaxLength(20)]
public string Asunto { get; set; }
[Required]
public string Detalle { get; set; }
[DataType(DataType.Date)]
public DateTime Fecha { get; set; }
[DataType(DataType.Time)]
public DateTime Hora { get; set; }
public virtual Local local { get; set; }
public virtual string username { get; set; }
}
我想删除一个“本地”,但我明白如果我想这样做,首先我必须摆脱“NotasAdjuntas”。
这是我的控制器(LocalsController)
// GET: Locals/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Local local = db.Locales.Find(id);
if (local == null)
{
return HttpNotFound();
}
return View(local);
}
// POST: Locals/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Local local = db.Locales.Find(id);
db.Locales.Remove(local);
db.SaveChanges();
return RedirectToAction("Index");
}
感谢任何帮助!
答案 0 :(得分:1)
你只需要用必需的属性标记“local”,这应该做(EF会生成正确的关系 - 在这种情况下是一对多)。意味着,如果您只是正确设置关系,它会为您自动删除“子”实体。
[Table("NotasAdjuntas")]
public class NotasAdjuntas
{
public int Id { get; set; }
....
[Required] //<<<<< add this
public virtual Local local { get; set; }
....
}
答案 1 :(得分:0)
删除本地之前删除备注条目。像这样:
public ActionResult DeleteConfirmed(int id)
{
foreach (var nota in local.notas)
{
var notaParaEliminar = db.NotasAdjuntas.find(nota.Id);
db.NotasAdjuntas.Remove(notaParaEliminar);
}
Local local = db.Locales.Find(id);
db.Locales.Remove(local);
db.SaveChanges();
return RedirectToAction("Index");
}