【问题标题】:Entity Framework 5: Cascade Delete One to ManyEntity Framework 5:级联删除一对多
【发布时间】:2016-11-09 14:22:32
【问题描述】:

我想知道当我想删除我的客户时如何删除我的所有银行支票。

这是我的数据库

我做了这样的事情:

ConEntities context = new ConEntities();
context.Customer.Attach(selectedCustomer);
context.Customer.Remove(selectedCustomer);
context.SaveChanges();
context.Dispose();

但我有这个错误:

无法删除或更新父行:外键约束失败 (``.BankCheck, 约束 fk_1 外键 (idCustomer) 参考Customer (id))"

我将 Cascade 放在 OnDelete End1 上

【问题讨论】:

  • 是什么让您断定异常与级联删除有关?它不是。看看selectedCustomer来自哪里。
  • 在我选择的客户中,我有我所有的银行支票。它来自我的数据网格。我的异常相关是当我的上下文尝试附加我的 selectedCustomer 时。
  • 你应该问问自己为什么它仍然附加到以前的上下文中。
  • 好的,我已经编辑了我的帖子。我现在还有一个错误。
  • 使用 INNODB 引擎 here 的数据库强制级联删除。这意味着数据库引擎会为您执行级联删除。

标签: mysql entity-framework-5


【解决方案1】:

this修复:

using (var context = new ConEntities())
{
    var parent = context.Customer.Include(p => p.Check).SingleOrDefault(s => s.id == selectedCustomer.id);

    if (parent.Check != null && parent.Check.Count > 0)
    {
        foreach (var child in parent.Check.ToList())
        {
            context.Check.Remove(child);
        }
    }

    context.Customer.Attach(parent);
    context.Customer.Remove(parent);
    context.SaveChanges();
}

【讨论】:

    猜你喜欢
    • 2016-01-17
    • 2017-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-09
    相关资源
    最近更新 更多