-1

I want to know how I can delete all my bankCheck when i want to delete my Customer.

This is my database

I made something like this:

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

But i have this error:

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

I put Cascade on my OnDelete End1

Naografix
  • 847
  • 2
  • 15
  • 35
  • What makes you conclude that the exception is related to cascaded delete? It isn't. Look at where `selectedCustomer` comes from. – Gert Arnold Jul 07 '16 at 10:23
  • In my selectedCustomer i have all my BankCheck. It come from my datagrid. And my exception related is when my context try to attach my selectedCustomer. – Naografix Jul 07 '16 at 11:40
  • You should ask yourself why it is still attached to the previous context. – Gert Arnold Jul 07 '16 at 12:16
  • Ok i have edited my post. I have an other error now. – Naografix Jul 07 '16 at 12:26
  • A database-enforced cascading delete with the INNODB engine [here](http://stackoverflow.com/a/32298405). This means the db engine does the cascading delete for you. – Drew Jul 08 '16 at 01:38

1 Answers1

0

Fixed with 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();
}
Community
  • 1
  • 1
Naografix
  • 847
  • 2
  • 15
  • 35