1

我正在开发一个 WP7 应用程序,我需要使用 DeleteOnSubmit() 方法删除一行,但我不断收到 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)

我在这里想念什么?

4

1 回答 1

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.
于 2012-09-23T12:05:31.240 回答