I have these two tables in my database, named Vendors and VendorPriceBreaks:
Vendors
-----------------
VendorID (PK)
Name
VendorPriceBreaks
-----------------
VendorPriceBreakID (PK)
VendorID (FK)
Price
When I delete a Vendor, I'd like to have all the VendorPriceBreaks associated with it deleted as well. I'm using Entity Framework.
I tried this first:
public RedirectToRouteResult Delete(int id)
{
MyEntities entities = new MyEntities();
var vendor = entities.Vendors.FirstOrDefault(v => v.VendorID == id);
entities.Vendors.Context.DeleteObject(vendor);
entities.Vendors.Context.SaveChanges();
return RedirectToAction("Index");
}
Which gave me the error message: The DELETE statement conflicted with the REFERENCE constraint "FK_VendorPriceBreaks_Vendors"
So then I added this line before I deleted my object: vendor.VendorPriceBreaks.Clear();
But then I got this error message: The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.
What's the best way to do this?