gpt4 book ai didi

c# - LINQ to SQL - 插入产生奇怪的行为

转载 作者:太空宇宙 更新时间:2023-11-03 11:49:08 25 4
gpt4 key购买 nike

我正在尝试将几个新创建的项目插入到数据库中。我有一个名为“Order”的 LINQ2SQL 生成类。

在订单内部,有一个名为“OrderItems”的属性,它也是由 LINQ2SQL 生成的,代表该订单的项目。

到目前为止一切顺利。我现在遇到的问题是,当我尝试在 Order 中添加多个新创建的 OrderItem 时。

即:

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 );
}

context.SubmitChanges();

不幸的是,只添加了一个实体。是的,我通过添加 Context.Log = Console.Out 检查了生成的 SQL,是的,只创建了一条语句。

有什么线索吗?顺便说一下,我知道我没有使用 InsertOnSubmit,文档说:

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.

非常感谢您的宝贵时间。

最佳答案

问题解决了。

问题是我天真地实现了 GetHashcode 方法。这意味着,它为已经创建的实体返回正确的哈希码,但对于新创建的实体(没有分配 ID),它返回相同的哈希码。

所以我禁用了 Equals 和 GetHashcode 的实现,但它运行得很好。感谢您的尝试 =)

关于c# - LINQ to SQL - 插入产生奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2534557/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com