[英]Entity Framework On Delete Cascade when entity is loaded
我在MySQL中使用Entity Framework 6 Code Firsts。
我具有以下實體和流利的配置:
public class Cotizacion
{
public int CotizacionId { get; set; }
public int Numero { get; set; }
public DateTime Fecha { get; set; }
public int? ClienteId { get; set; }
public Cliente Cliente { get; set; }
public List<ItemsCotizacion> Items { get; set; }
}
public class Cliente
{
public int ClienteId { get; set; }
public string RazonSocial { get; set; }
public string Cuit { get; set; }
public string Direccion { get; set; }
public string Telefono { get; set; }
public List<Cotizacion> Cotizaciones { get; set; }
}
public class ConfigCliente : EntityTypeConfiguration<Cliente>
{
public ConfigCliente()
{
Property(c => c.RazonSocial).IsRequired().HasMaxLength(100);
Property(c => c.Direccion).IsOptional().HasMaxLength(100);
Property(c => c.Cuit).IsOptional().HasMaxLength(15);
Property(c => c.Telefono).IsOptional().HasMaxLength(100);
HasKey(c => c.ClienteId);
HasMany(c => c.Cotizaciones).WithRequired(cot => cot.Cliente).WillCascadeOnDelete(true);
}
}
public class ConfigCotizacion : EntityTypeConfiguration<Cotizacion>
{
public ConfigCotizacion()
{
Property(c => c.Fecha).IsRequired();
HasRequired(c => c.Items);
HasMany(c => c.Items).WithRequired(i => i.Cotizacion).WillCascadeOnDelete(true);
HasRequired(c => c.Cliente).WithMany(cot => cot.Cotizaciones);
}
}
我希望當我刪除實體“ Cliente”時EF刪除所有相關實體“ Cotizacion”。僅當我在上下文中加載列表Cotizaciones時,級聯刪除才會失敗,但是當我不在上下文中加載Cotizaciones列表時,級聯刪除將失敗刪除工作正常。
我收到以下錯誤:
{“無法添加或更新子行:外鍵約束失敗(\\“ pruebaentity \\”。\\“ cotizacion \\”,CONSTRAINT \\“ FK_Cotizacion_Cliente_ClienteId \\” FOREIGN KEY(\\“ ClienteId \\”)參考\\“ cliente \\”( \\“ ClienteId \\”)在更新級聯上刪除級聯)“}
解決:問題是我用過
context.Entry(entity).Sate = System.Data.Entity.EntityState.Deleted
代替
context.Clients.Remove(entity)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.