【问题标题】:Deleting Children and Parents in MVC4 with EF Codefirst使用 EF Code First 在 MVC 4 中删除子项和父项
【发布时间】:2013-02-03 11:48:08
【问题描述】:

我有一些父/子关系如下:

public class Card
{
    public virtual int CardId { get; set; }
    public virtual Set ParentSet { get; set; }
    public virtual IList<Side> Sides { get; set; }
}

public class Set
{
    public virtual int SetId { get; set; }
    public virtual Set ParentSet { get; set; }
    public virtual IList<Card> Cards { get; set; }
}

public class Side
{
    public virtual int SideId { get; set; }
    public virtual Card ParentCard { get; set; }
}

所以,一套包含包含边的卡片。一个 Set 还可以包含其他 Set。

我尝试创建一个基本的删除控制器操作:

public ActionResult DeleteConfirmed(int cardId)
{
    Card card = _db.Cards.FirstOrDefault(c => c.CardId == cardId);
    if (card == null)
    {
        return HttpNotFound();
    }

    _db.Cards.Remove(card);
    _db.SaveChanges();
    return RedirectToAction("Detail", "Set", new {setId = card.ParentSet.SetId});
}

但是我得到一个错误 DbUpdateException:

“保存不为其关系公开外键属性的实体时发生错误。EntityEntries 属性将返回 null,因为无法将单个实体标识为异常源。可以更轻松地在保存时处理异常通过在您的实体类型中公开外键属性。”

如果需要,我可以在此处发布详细信息,但我感觉这是与我的模型或配置有关的问题。我想我不必为每个使父 FK 无效的实体构建级联删除方法......对吗?

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3 entity-framework asp.net-mvc-4


    【解决方案1】:

    您看到此错误是因为您想使用 Forgein Key 删除项目。

    您应该删除 Card==Deleting Card 的所有面。

    Here You can find more information about deleting in EF

    【讨论】:

      猜你喜欢
      • 2013-08-03
      • 2011-10-26
      • 2012-01-28
      • 1970-01-01
      • 1970-01-01
      • 2014-07-18
      • 1970-01-01
      • 2016-12-18
      • 1970-01-01
      相关资源
      最近更新 更多