开发者

Linq to SQL Insert Error

An attempt has been made to Attach or Add an entity that is not new, perhaps having been loaded from another DataContext. This is not supported.

This is the error message I am getting when I try to run the following, roughly:

1 DataContext db = new DataContext();
2 o = new obje开发者_StackOverflow社区ct();
3 o.association = db.GetAssociatedObject(pId);
4 db.objects.InsertOnSubmit(o);
5 db.SubmitChanges();

This code creates a new object, populates an association with an existing object, then inserts the new object. When I comment out line 3+4, the error goes away. What causes the error? Can I not do an insert with associated objects?


This is probably because you are maintaining a bidirectional relationship between o and its associated object. When you tell the DataContext to Insert o, its associated object is duplicated in the DataContext's object tracking graph (one time as loaded and another time as Insert for o).

Commenting out line 4 should resolve the issue, but leave you with a correct association between o and o.association.


The error message is misleading. This is a bit more complicated, but I found the error.

I have a method that is trying to save a detached object, and create associations for it. This method creates a new attached copy of the object and copies all the members. It then creates the association.

Say I have object A that is detached. My method tries to read it from database so that I have the attached version of it. Say this is object A. A is being updated with all the members that changed. A needs to get an association with objects of type C, via a many-to-many relationship called B: A <= B => C

I assigned the detached copy of A to B. This caused the exception. Once I assigned the correct instance of A, it worked.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜