开发者

LINQ to SQL - Insert yielding strange behavior

I'm trying to insert several newly created items to the database. I have a LINQ2SQL generated class called "Order".

Inside order, there's a property called "OrderItems" which is also generated by LINQ2SQL and represents the Items of that Order.

So far so good. The problem I'm having right now, is when I try to add more than one newly created OrderItem inside Order.

I.E:

Order o = orderWorker.GetById( 10 ); 
for( int i=0; i < 5; ++i ) {
  OrderItem oi =new OrderItem {
                Order = o,
                Price = 100,
                ShippingPrice = 100,
                ShippingMethod = ...,
                Item = someItem
            };
  o.OrderItems.Add( oi );
}

开发者_JAVA技巧context.SubmitChanges();

Unfortunately, only a single entity is being added. Yes, I checked the generated SQL by adding Context.Log = Console.Out, and yes, only one statement was created.

Any clues? By the way I know I'm not using InsertOnSubmit, by the documentation says:

You can explicitly request Inserts by using InsertOnSubmit. Alternatively, LINQ to SQL can infer Inserts by finding objects connected to one of the known objects that must be updated. For example, if you add an Untracked object to an EntitySet(TEntity) or set an EntityRef(TEntity) to an Untracked object, you make the Untracked object reachable by way of tracked objects in the graph. While processing SubmitChanges, LINQ to SQL traverses the tracked objects and discovers any reachable persistent objects that are not tracked. Such objects are candidates for insertion into the database.

Thank you very much for your time.


Problem solved, sort of.

The problem was that I implemented the GetHashcode method naively. Meaning, it was returning proper hashcodes for entities that were already created, but for newly created entities (which had no assigned ID's) it was returning the same hashcode.

So I disabled my implementation of Equals & GetHashcode, and it worked just fine. Thank you for trying =)


This might sound crazy, but I wonder if it will work differently if you remove the Order = o assignment, and just add it to the OrderLines collection. Give it a try, at least.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜