An attempt was made to nest or add an object that is not a new Linq to Sql error

I have a save function for my order object that looks like this and it splits into 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 objects; address object and credit card object. Now I want these two objects to sometimes be null.

Now my hunch about why this is causing the error is that both of these elements, which are inside the order, are null. If so, how can I insert a new order into a database with two objects (Address and creditCard) that are null.

Edit:

So, I deleted the object and credit card address at the moment, but I realized what was causing the problem. There is a collection of images in the order (an image is an entity), and it throws an error because (im accepts) that I cannot insert a new order with an order having a bunch of already existing images. So I know what the problem is, but I have no idea how to fix it. Any help is appreciated. Thanks

+4
source share
2 answers

Were your image objects derived from another DataContext? As long as they come from the same DataContext that you use to save your order, you should not try to add them again.

+4
source

It is assumed that the address and credit card are already known to Linq to SQL, however, when you tell it to β€œInsert order” (which contains the address and credit card), Linq to SQL will also try to insert these two sides (this does this for the whole chart).

I assume that you need to either: a) make sure that you are not attaching existing entites to the new one, or b) insert the new object first, and then connect your connection.

+2
source

Source: https://habr.com/ru/post/1342207/


All Articles