【问题标题】:Cascade delete in EF5.0 code first approach parent table not deleting properly?EF5.0 代码中的级联删除优先处理父表未正确删除?
【发布时间】:2013-10-20 10:42:52
【问题描述】:

我已使用 Entity Framework 5.0 代码优先方法将级联删除定义到子模型。 现在对父表记录执行删除操作时,相应的子表记录不会被删除。子表有来自父表的外键引用。 在下面我附上我的模型代码:

//"Product" parent class
public class Product
{
   [Key, Column(Order = 0)]
   [Required]
   [MaxLength(50)]
   public string Upc { get; set; }

   public double Height { get; set; }
   public double Width { get; set; }
   public virtual List<ProductImages> ProductImages { get; set; }

   public Product()
   {
       this.ProductImages = new List<ProductImages>();
   }
}


//"ProductImages" child class
public class ProductImages
{     
   [Key, Column(Order = 0)]
   public string Upc { get; set; }
   [ForeignKey("Upc")]
   public virtual Product Product { get; set; }
   [Key, Column(Order = 1)]
   public short Orientation { get; set; }
}

//Cascade delete constraint
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
   base.OnModelCreating(modelBuilder);
   modelBuilder.Entity<Product>()
              .HasMany(t => t.ProductImages)
              .WithRequired()
              .HasForeignKey(d => d.Upc)
              .WillCascadeOnDelete(true);
}

删除记录时,我在
context.SaveChanges();

收到以下错误

错误

操作失败:无法更改关系,因为一个或多个 的外键属性是不可为空的。当关系发生变化时 在船上,相关的外键属性设置为空值。如果外国—— key 不支持空值,必须定义新的关系,foreig n-key 属性必须被分配另一个非空值,或者不相关的对象 必须删除。

谁能帮我一次删除父表记录和子表记录?

谢谢, Sampath。

【问题讨论】:

  • 你能展示你如何删除父级的代码吗? (点击问题下方的“编辑”链接)

标签: c# entity-framework-5


【解决方案1】:

您的映射不正确。您必须为反向导航属性 ProductImages.Product 提供表达式,而不是不带参数的 .WithRequired():

.WithRequired(d => d.Product)

您必须使用WithRequired 的无参数版本仅当您的实体不具有反向导航属性。

【讨论】:

  • 嗨,我已经尝试通过修改上面的代码行。我仍然遇到同样的问题。请帮助我谢谢,sampath
猜你喜欢
  • 2014-11-24
  • 1970-01-01
  • 1970-01-01
  • 2012-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多