Reputation: 77
I tried to delete row in datagrid but I noticed that in my database my foreign keys are set ON DELETE NO ACTION so many examples from the internet didn't work. In every row in datagrid I have a delete button. Whenever I click on it I get an error
SqlException: The DELETE statement conflicted with the REFERENCE constraint "ulice_idprzystanku_fkey". The conflict occurred in database RozklaJazdyKM...
Is there any other solution to delete the rows?
private void DeletePrzystanek(przystanki przystanki)
{
//if (dni != null)
//{
var przystanek = (from p in bazaDanych.przystanki.Local
where p.idprzystanku == przystanki.idprzystanku
select p).FirstOrDefault();
foreach (var item in przystanek.relacje.ToList())
{
bazaDanych.relacje.Remove(item);
}
foreach (var item in przystanek.przejazdy.ToList())
{
bazaDanych.przejazdy.Remove(item);
}
bazaDanych.przystanki.Remove(przystanek);
bazaDanych.SaveChanges();
przystankiViewSource.View.Refresh();
//}
}
private void DeleteCommandHandler(object sender, ExecutedRoutedEventArgs e)
{
przystanki p = e.Parameter as przystanki;
DeletePrzystanek(p);
}
The code is from Microsoft docs:
private void Delete_Order(Order order)
{
var ord = (from o in context.Orders.Local
where o.OrderID == order.OrderID
select o).FirstOrDefault();
foreach (var detail in ord.Order_Details.ToList())
{
context.Order_Details.Remove(detail);
}
context.Orders.Remove(ord);
context.SaveChanges();
ordViewSource.View.Refresh();
}
private void DeleteOrderCommandHandler(object sender, ExecutedRoutedEventArgs e)
{
Order obj = e.Parameter as Order;
Delete_Order(obj);
}
Upvotes: 0
Views: 942
Reputation: 1520
By the looks of it, it seems you are trying to delete a row that already has children, I mean a row which is referenced by other entities. You have specified OnDelete: NoAction
That means it would be a problem for the rows of other tables when you delete the row they currently reference. What you can do is to delete all the related entities first before deleting that row. For example, if you're trying to delete a bazaDanych
entity with an Id of 7. You want to check if it is referenced by other rows in the Rozkla...
table
var rozks = _context.RozklaJazdyKMs.Where(r = r.bazaDanychId == 7);
_context.RozklaJazdyKMs.RemoveRange(rozks);
_context.SaveChanges();
Then you can safely delete the bazaDanych
entity since the entities referencing it are now deleted.
The other way and right thing to do is to simply configure CascadeOnDelete
to Delete
Upvotes: 1