0

I was trying to implement the Delete Action in the MVC3, but I got to the point that the object that I want to delete has dependencies in other tables and that's why I am getting:

DELETE statement conflicted with the REFERENCE constraint

Here is my method in the controller:

[HttpPost]
public ActionResult Delete(int? id)
{
    repo.DeleteDirector(id);
    return View("index");
}

and this is how I am deleting it in my repository:

void DeleteDirector(int? id)
{
    Director d = dc.Directors.FirstOrDefault(dir => dir.Id == id);
    dc.Directors.Remove(d);
    dc.SaveChanges();
}

I was hoping that simple LINQ Remove method will do the job, but it won't. So I am trying to think of a way to efficiently remove it with all the dependencies. I know that I can do it manually by going through all the tables where particular Director might be referenced. But I was hoping if Framework provides own implementation for it.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
inside
  • 3,047
  • 10
  • 49
  • 75

1 Answers1

2

There is one property in SQL CasCade delete which will enable dependencies to be deleted automatically when the parent record removed from the table.

By reviewing above code I am assuming you are using EF code first with repository pattern. If this is the case then you should provide Cascade delete in configuration. you can refer the below link

Entity Framework (EF) Code First Cascade Delete

I hope that will be helpful to you.

Community
  • 1
  • 1
Jenish Rabadiya
  • 6,708
  • 6
  • 33
  • 62