2011-11-26 90 views
1

這是我的計劃錯誤刪除對象+關係一對多+的LINQ to SQL

一個對象之間的關係和SectionObject是一對多和兩個表之間的關係是基於的ObjectId。

第一:一套OBJ

private void ObjectAdd(...) 
{ 
    obj = new Object(); //is Public 
    obj = Shop.Objects.SingleOrDefault(S => S.IdObject == SelectedObjectId); 
} 

謝勝利:添加sectionObject在OBJ

private void BtnAddCategory(...) 
{ 
    SectionObject SO = new SectionObject(); 
       SO.Section = Shop.Sections.SingleOrDefault(Sections => Sections.SectionId == FrmCategoryList.SelectedSectionId); 

    obj.SectionObjects.Add(SO); 
} 

三:刪除SectionObject obj的

private void BtnDelCategory(...) 
{ 
    SectionObject SO = new SectionObject(); 
       SO = obj.SectionObjects.SingleOrDefault(Sections => Sections.SectionId == Convert.ToInt32(dataGridView1.SelectedRows[0].Cells[0].Value)); 

    obj.SectionObjects.Remove(SO); 
} 

決賽:插入OBJ數據庫

private void BtnAccept(...) 
{ 
    Shop.Objects.InsertOnSubmit(obj); 
    Shop.SubmitChanges(); // ERROR 
} 

錯誤是:

System.InvalidOperationException was caught 
    Message=An attempt was made to remove a relationship between a Object and a SectionObject. However, one of the relationship's foreign keys (SectionObject.ObjectId) cannot be set to null. 
    Source=System.Data.Linq 
    StackTrace: 
     at System.Data.Linq.ChangeTracker.StandardChangeTracker.StandardTrackedObject.SynchDependentData() 
     at System.Data.Linq.ChangeProcessor.ValidateAll(IEnumerable`1 list) 
     at System.Data.Linq.ChangeProcessor.SubmitChanges(ConflictMode failureMode) 
     at System.Data.Linq.DataContext.SubmitChanges(ConflictMode failureMode) 
     at WindowsFormsApplication1.ObjectAdd.BtnAccept_Click(Object sender, EventArgs e) in C:\Users\EasySoft\Documents\Visual Studio 2010\Projects\Shop 90.08.22\Shop10.4\Shop\ObjectAdd.cs:line 47 
    InnerException: 

回答

0

當你創建你需要設置它的sectionobject.objectid屬性的對象的sectionobject。 如果您在添加後直接進行更改,則會得到相同的錯誤。這是告訴你有沒有foriegn密鑰對象

+0

我使用此代碼,但未解決 SectionObject SO = new SectionObject(); SO.ObjectId = obj.objectId; SO.Section = Shop.Sections.SingleOrDefault(Sections => Sections.SectionId == FrmCategoryList.SelectedSectionId); obj.SectionObjects.Add(SO); – Mehrdad