Collin O'Connor
Collin O'Connor

Reputation: 1351

An attempt has been made to Attach or Add an entity that is not new Linq to Sql error

I have a save function for my order entity that looks like this and it breaks on the sumbmitChanges line:

public void SaveOrder ( Order order ) {
    if (order.OrderId == 0)
        orderTable.InsertOnSubmit(order);
    else if (orderTable.GetOriginalEntityState(order) == null) {
        orderTable.Attach(order);
        orderTable.Context.Refresh(RefreshMode.KeepCurrentValues , order);
    }
    orderTable.Context.SubmitChanges();
}

The order entity contains two other entities; an Address entity and a credit card entity. Now i want these two entities to be null sometimes.

Now my guess for why this is throwing an error is because that both of these entites that are inside order are null. If this is the case, How can I insert an new order into the database with both entities (Address and creditCard) being null.

Edit:

So i deleted the credit card entity and address entity for now, but i realized what is causing the problem. The order has a collection of Images (an Image is an entity), and it throws the error because (im assuming), that i cant insert a new order with the order having a bunch of images that already exist. So i know what the problem is, but i have no idea how to fix it. Any help would be much appreciated. Thanks

Upvotes: 4

Views: 6424

Answers (2)

Brian Cauthon
Brian Cauthon

Reputation: 5534

Did your image entities come from a different DataContext? As long as they come from the same DataContext that your are using to save your order it should not try to add them again.

Upvotes: 4

Johannes Rudolph
Johannes Rudolph

Reputation: 35761

The proplem is that the Adress and Credit card are already known to Linq to SQL, however when you tell it to Insert the order (which holds adress and credit card) Linq to SQL would attempt to insert those two entites too (it does so for the whole Graph).

My guess would be that you need either need to a) make sure you're not attaching existing entites to a new one or b) first insert the new entity and then wire up your association.

Upvotes: 2

Related Questions