本文介绍了如何在Entity Framework CF之前删除子实体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用EF代码,首先删除一个数据库记录( deleteMe )和它的孩子( deleteMe.Prices )。

I am trying to use EF code-first to delete a db record (deleteMe) and it's children (deleteMe.Prices).

foreach (var deleteMe in deleteThese)
{
   // Delete validation
   if(CanDeleteItem(deleteMe.ItemId))
   {
      db.Entry(deleteMe).State = EntityState.Deleted;

      foreach (var item in deleteMe.Prices)
      {
         db.Entry(item).State = EntityState.Deleted; // cascade delete
      }
   }
}
db.SaveChanges();

但是,Entity Framework似乎无法跟踪子记录应该在父母。我收到错误:

However, Entity Framework seems to be unable to track the fact that the child records should be deleted before the parent. I get the error:

我如何在EF中执行这个删除?

How would I execute this delete in EF?

推荐答案

d为我做:

foreach (var deleteMe in deleteThese)
{
   // Delete validation
   if(CanDeleteItem(deleteMe.ItemId))
   {
      ///
      deleteMe.Prices.ToList().ForEach(p => db.ItemPrices.Remove(p));
      ///

      db.Entry(deleteMe).State = EntityState.Deleted;
   }
}
db.SaveChanges();

这篇关于如何在Entity Framework CF之前删除子实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-13 01:56