2015-07-12 125 views
0

即時通訊使用實體框架6代碼優先與MySQL。實體框架在刪除時實體被加載時級聯

我有以下實體和流利的配置:

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」 .The級聯刪除只有當我加載失敗在上下文中列出Cotizaciones,但是當我不在上下文中加載Cotizaciones列表時,級聯刪除可以正常工作。

我收到以下錯誤:

{"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)"}

回答

0

解決: 問題是,我用的

context.Clients.Remove(entity) 

context.Entry(entity).Sate = System.Data.Entity.EntityState.Deleted 

代替