[英]Entity Framework On Delete Cascade when entity is loaded
im using Entity Framework 6 Code Firsts with MySQL. 我在MySQL中使用Entity Framework 6 Code Firsts。
I have the following entities and fluent configurations: 我具有以下实体和流利的配置:
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);
}
}
I want that when i delete an entity "Cliente" EF Deletes all the related entities "Cotizacion" .The cascade delete fails ONLY when i load the List Cotizaciones in the context , but when i dont load the Cotizaciones list in the context, the cascade delete works fine. 我希望当我删除实体“ Cliente”时EF删除所有相关实体“ Cotizacion”。仅当我在上下文中加载列表Cotizaciones时,级联删除才会失败,但是当我不在上下文中加载Cotizaciones列表时,级联删除将失败删除工作正常。
I get the following Error: 我收到以下错误:
{"Cannot add or update a child row: a foreign key constraint fails (\\"pruebaentity\\".\\"cotizacion\\", CONSTRAINT \\"FK_Cotizacion_Cliente_ClienteId\\" FOREIGN KEY (\\"ClienteId\\") REFERENCES \\"cliente\\" (\\"ClienteId\\") ON DELETE CASCADE ON UPDATE CASCADE)"}
{“无法添加或更新子行:外键约束失败(\\“ pruebaentity \\”。\\“ cotizacion \\”,CONSTRAINT \\“ FK_Cotizacion_Cliente_ClienteId \\” FOREIGN KEY(\\“ ClienteId \\”)参考\\“ cliente \\”( \\“ ClienteId \\”)在更新级联上删除级联)“}
Solved: The problem was that i used 解决:问题是我用过
context.Entry(entity).Sate = System.Data.Entity.EntityState.Deleted
instead of 代替
context.Clients.Remove(entity)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.