3

我的模型如图所示。

在此处输入图像描述

代码:

            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();


            }

当我运行此代码时,它会在 WFE.SaveChanges 行出错,并出现以下错误。

System.InvalidOperationException:操作失败:无法更改关系,因为一个或多个外键属性不可为空。当对关系进行更改时,相关的外键属性将设置为空值。如果外键不支持空值,则必须定义新关系,必须为外键属性分配另一个非空值,或者必须删除不相关的对象。在 System.Data.Objects.ObjectContext.SaveChanges(SaveOptions 选项)
在 System.Data.Entity.Internal.InternalContext.SaveChanges() 在 System.Data.Entity.Internal.LazyInternalContext.SaveChanges() 在 System.Data.Entity.DbContext.SaveChanges() 在 ManageBusinessAreas.MainWindow.ButtonDeleteBusinessArea_Click(对象发件人, c:\TFS_Source\SharedApps\AdminProcesses\ManageBusinessAreas\ManageBusinessAreas\ManageBusinessAreas\MainWindow.xaml.cs:line 249 中的 RoutedEventArgs e)

我查看了其他帖子,不幸的是,这些修复要么不适用于我,要么不起作用。任何帮助将不胜感激。

4

1 回答 1

2

发现了问题。而不是从 myBusinessAreas 的 Processes Navigation 中删除 myProcess,我需要将它从我的上下文的 Processes Entity 中删除。

于 2013-09-10T14:53:48.027 回答