Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove and then add child items in LINQ to SQL

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()
like image 861
Eduardo Molteni Avatar asked Mar 11 '09 16:03

Eduardo Molteni


2 Answers

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

db.OrderItems.DeleteAllOnSubmit(o.Items);
like image 95
ScottS Avatar answered Nov 08 '22 11:11

ScottS


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
like image 30
Eduardo Molteni Avatar answered Nov 08 '22 09:11

Eduardo Molteni