0

im using Entity Framework 6 Code Firsts with MySQL.

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.

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

Mitch
  • 21,223
  • 6
  • 63
  • 86

1 Answers1

0

Solved: The problem was that i used

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

instead of

context.Clients.Remove(entity)