mysql - Entity Framework 5 : Cascade Delete One to Many

标签 mysql entity-framework-5

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

这是我的数据库

我做了这样的事情:

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

但是我有这个错误:

Cannot delete or update a parent row: a foreign key constraint fails (``.BankCheck, CONSTRAINT fk_1 FOREIGN KEY (idCustomer) REFERENCES Customer (id))"

我将 Cascade 放在 OnDelete End1 上

最佳答案

已修复 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();
}

关于mysql - Entity Framework 5 : Cascade Delete One to Many,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38242538/

相关文章:

php - 上传图像的 zip 文件夹,然后使用 php 将它们转换为缩略图

mysql - 使用唯一索引插入重复数据

ef-code-first - Entity Framework 代码优先迁移 - 启用迁移失败

php - 搜索邮政编码可以在线但不能离线(从本地数据库)

Mysql - 查询的排名字段

mysql - 如何对关联表进行 FLASK SQLALCHEMY 查询

c# - 什么是独立协会和外键协会?

c# - 撤消对数据库表的更新

.net - 使用复合键在模型中创建关系会引发 "Property is part of key and can' t be modded”异常

entity-framework - 查询实体在枚举字段上抛出 "Invalid Operation Exception"