My Model is as show in the image.
Code:
App MyApp = (App)Application.Current;
WFE = new WorkflowMenuEntities();
WFE.Database.Connection.ConnectionString = MyApp.WorkflowMenuEntityConnectionString;
string Input = Microsoft.VisualBasic.Interaction.InputBox("Deleting this Business Area will delete ALL processes associated with it. If you are sure you wish to continue please type in delete and press ok.", "Confirm Deletion");
if (Input == "delete")
{
int BusinessID = ((BusinessArea)ComboboxBusinessArea.SelectedItem).ID;
BusinessArea myBusinessArea = WFE.BusinessAreas.Where(BA => BA.ID == BusinessID).FirstOrDefault();
foreach (var myProcesses in myBusinessArea.Processes.ToList())
{
foreach (var myWorkerProcess in myProcesses.WorkerProcesses.ToList())
{
myProcesses.WorkerProcesses.Remove(myWorkerProcess);
}
myBusinessArea.Processes.Remove(myProcesses);
}
foreach (var myADGroup in myBusinessArea.ADGroups.ToList())
{
myBusinessArea.ADGroups.Remove(myADGroup);
}
WFE.BusinessAreas.Remove(myBusinessArea);
WFE.SaveChanges();
BuildBusinessAreaList();
}
When ever I run this code it errors out at the WFE.SaveChanges line with the below error.
System.InvalidOperationException: 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. at System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options)
at System.Data.Entity.Internal.InternalContext.SaveChanges() at System.Data.Entity.Internal.LazyInternalContext.SaveChanges() at System.Data.Entity.DbContext.SaveChanges() at ManageBusinessAreas.MainWindow.ButtonDeleteBusinessArea_Click(Object sender, RoutedEventArgs e) in c:\TFS_Source\SharedApps\AdminProcesses\ManageBusinessAreas\ManageBusinessAreas\ManageBusinessAreas\MainWindow.xaml.cs:line 249
I've looked at other posts and unfortunately the fixes either didn't apply to me or they didn't work. Any help would be greatly appreciated.
Discovered the issue. Instead of removing the myProcess from the Processes Navigation of the myBusinessAreas I need to remove it from the Processes Entity of my context.