Entity Framework5:级联删除一对多

Entity Framework 5: Cascade Delete One to Many

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

这是我的数据库

我做了这样的东西:

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