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

asp.net-mvcclinq-to-sql

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

Best Answer

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.