C# 删除另一个表实体框架中的fk对象
我正在尝试删除另一个表中引用的对象 我试图删除的对象:C# 删除另一个表实体框架中的fk对象,c#,asp.net-mvc,entity-framework,C#,Asp.net Mvc,Entity Framework,我正在尝试删除另一个表中引用的对象 我试图删除的对象: [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")] p
[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; }
我想删除一个“Local”,但我明白如果我想这样做,首先我必须去掉“NotasAdjuntas”
这是我的控制器(LocalsController)
感谢您的帮助 在删除本地文件之前删除notes条目。大概是这样的:
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");
}
您只需要用required属性标记“local”,就可以了(EF将生成适当的关系——在这种情况下是一对多)。也就是说,如果您只是正确地设置了关系,它将为您自动删除“子”实体
[Table("NotasAdjuntas")]
public class NotasAdjuntas
{
public int Id { get; set; }
....
[Required] //<<<<< add this
public virtual Local local { get; set; }
....
}
[表(“NotasAdjuntas”)]
公营军
{
公共int Id{get;set;}
....
[必需]//尝试删除本地条目时是否出现异常?
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");
}
[Table("NotasAdjuntas")]
public class NotasAdjuntas
{
public int Id { get; set; }
....
[Required] //<<<<< add this
public virtual Local local { get; set; }
....
}