2012-09-22 39 views
1

我正在WP7應用程序中,我需要刪除使用DeleteOnSubmit()方法的行,但我不斷收到NullReferenceException錯誤。我找不到問題所在。WP7 LINQ刪除不工作 - 獲取NullReferenceException

public void HardDeleteOrder(int deleteOrderId) 
{ 

    var oResult = from o in App.orderDataContext.orders 
       where o.OrderId == deleteOrderId 
       select o; 


    foreach (var oRow in oResult) 
    { 
     App.orderDataContext.Orders.DeleteOnSubmit(oRow); 
    } 
    App.orderDataContext.SubmitChanges(); 
} 

當我運行此代碼崩潰的方法的結束大括號中的異常消息「NullReferenceException未處理」。

這裏的堆棧跟蹤:

System.NullReferenceException was unhandled 
Message=NullReferenceException 
StackTrace: 
    at System.Data.Linq.Mapping.MetaAccessor`2.SetBoxedValue(Object& instance, Object value) 
    at System.Data.Linq.ChangeProcessor.ClearForeignKeysHelper(MetaAssociation assoc, Object trackedInstance) 
    at System.Data.Linq.ChangeProcessor.ClearForeignKeyReferences(TrackedObject to) 
    at System.Data.Linq.ChangeProcessor.PostProcessUpdates(List`1 insertedItems, List`1 deletedItems) 
    at System.Data.Linq.ChangeProcessor.SubmitChanges(ConflictMode failureMode) 
    at System.Data.Linq.DataContext.SubmitChanges(ConflictMode failureMode) 
    at System.Data.Linq.DataContext.SubmitChanges() 
    at orders.viewmodels.OrderViewModel.HardDeleteOrder(Int32 deleteOrderId) 
    at orders.OrderView.RemoveOrderFromDatabase() 
    at orders.OrderView.RemoveOrder() 
    at orders.OrderView.detailsBarCancel_Click(Object sender, EventArgs e) 
    at orders.App.detailsBarCancel_Click(Object sender, EventArgs e) 
    at Microsoft.Phone.Shell.ApplicationBarItemContainer.FireEventHandler(EventHandler handler, Object sender, EventArgs args) 
    at Microsoft.Phone.Shell.ApplicationBarIconButton.ClickEvent() 
    at Microsoft.Phone.Shell.ApplicationBarIconButtonContainer.ClickEvent() 
    at Microsoft.Phone.Shell.ApplicationBar.OnCommand(UInt32 idCommand) 
    at Microsoft.Phone.Shell.Interop.NativeCallbackInteropWrapper.OnCommand(UInt32 idCommand) 

缺少什麼我在這裏?

回答

0

這主要是由於外鍵約束。 據 http://msdn.microsoft.com/en-us/library/bb386925.aspx

的LINQ to SQL不支持或識別級聯刪除操作。如果要刪除表中有約束條件的行,則必須完成以下任一操作:

Set the ON DELETE CASCADE rule in the foreign-key constraint in the database. 

Use your own code to first delete the child objects that prevent the parent object from being deleted.