I have an Asp.Net MVC 5 website with EntityFramework Code First. In my site, I have a Restaurant
model with the following code:
public class Restaurant
{
[Required]
public string Name { get; set; }
//....
public virtual IList<RestaurantType> Types { get; set; }
}
And the code for the RestaurantType
is:
public class RestaurantType
{
[Key]
public int ID { get; set; }
[Required]
public string Type { get; set; }
public virtual Restaurant Restaurant { get; set; }
}
When I try to delete the restaurant
from context, I get the following error:
The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.RestaurantTypes_dbo.Restaurants_Restaurant_ID". The conflict occurred in database "aspnet-Test-20131111052251", table "dbo.RestaurantTypes", column 'Restaurant_ID'.
The statement has been terminated.
I have data in production and I want to handle this as silently as possible. I tried the following code:
for (int i = 0; i < restaurant.Types.Count; i++)
{
var type = restaurant.Types[i];
db.RestaurantTypes.Remove(type);
restaurant.Types.Remove(type);
}
db.Restaurants.Remove(restaurant);
await db.SaveChangesAsync();
But I get the same error. I checked the database and there's no row with the restaurant ID. I even tried this:
var list = db.RestaurantTypes.Where(t => t.Restaurant == null || t.Restaurant.ID == restaurant.ID);
foreach (var ib in list)
{
db.RestaurantTypes.Remove(ib);
}
db.SaveChanges();
It didn't work either. Is there a way for me to fix this with C# code?