实体框架5:级联删除一对多

问题描述:

我想知道当我想删除我的客户时,如何删除我所有的银行检查。实体框架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))"

我把级联我OnDelete End1

+0

是什么让你得出这样的结论,以级联删除异常有关系吗?事实并非如此。看看'selectedCustomer'的来源。 –

+0

在我所选的客户中,我拥有所有的BankCheck。它来自我的数据网格。和我的例外情况相关的是当我的上下文尝试附加我选择的客户。 – Naografix

+0

你应该问自己为什么它仍然与前面的背景有关。 –

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