views:

1669

answers:

2

I have a serie of child items of a table, that I wan't to delete and then add the new ones.
I don't care about performance, because it is a non frequent operation.

How must I do it? I have tried Order.items.clear() and Order.Items.Remove(x) but both give me exceptions

Simplified code:

    Dim db As New MainDataDataContext
    dim o as Order = (From Order In db.Orders Where Order.OrderID = OrderID).FirstOrDefault
    ''//this will return "An attempt was made to remove a 
    ''//relationship between a Order and a OrderItem. 
    ''//However, one of the relationship's foreign keys 
    ''//(Order.OrderID) cannot be set to null." exception
    o.Items.Clear()
    ''//and this will return "EntitySet was modified during enumeration." exception
    For Each oItem As OrderItem In o.Items
        o.items.Remove(oItem)
    Next

    For Each item As ListViewItem In listViewOrderItems.Items
        If item.ItemType = ListViewItemType.DataItem Then
            Dim oItem As New OrderItem
            oItem.OrderID = OrderID
            oItem.Product = CType(item.FindControl("txtProduct"), TextBox).Text
            oItem.Quantity = CType(item.FindControl("txtQuantity"), TextBox).Text
            Order.items.Add(oItem)
        End If
    Next

    db.SubmitChanges()
A: 

Nevermind, I found the solution (but don't know if it is the best)

For Each oItem As OrderItem In o.Items
    db.OrderItems.DeleteOnSubmit(oItem)
Next
Eduardo Molteni
+5  A: 

As long as you are removing all the Items you may as well use

db.OrderItems.DeleteAllOnSubmit(o.Items);
ScottS