【问题标题】:Entity Framework On Delete Cascade when entity is loaded加载实体时删除级联的实体框架
【发布时间】:2015-10-01 00:48:36
【问题描述】:

我在 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\", 约束 \"FK_Cotizacion_Cliente_ClienteId\" 外键 (\"ClienteId\") 参考 \"cliente\" (\"ClienteId\") ON DELETE CASCADE ON UPDATE 级联)"}

【问题讨论】:

    标签: c# mysql entity-framework


    【解决方案1】:

    已解决: 问题是我用了

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

    而不是

    context.Clients.Remove(entity)
    

    【讨论】:

      猜你喜欢
      • 2014-12-20
      • 1970-01-01
      • 2012-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多