我正在使用NHibernate进行一些测试,我目前有两个映射实体,Orders和Products.一如既往,Order有一系列产品,我将其映射为:
<bag name="Products" cascade="all" lazy="true"> <key column ="Order_ID" /> <many-to-many class="Product" column="Product_ID" /> </bag>
在C#方面:
public virtual IList<Product> Products { get { return _Products; } set { _Products = value; } } private IList<Product> _Products = new List<Product>();
如果我在数据库中有一个持久订单(约翰的订单),其产品集合中有一些项目(苹果,橙子和椰子),我尝试在集合中添加一个新项目(香蕉)我可以看到从sql输出中,NHibernate正在做这样的事情:
INSERT INTO Products_Table (Product_Name,Product_ID) VALUES ('Banana',@Banana_ID) DELETE FROM Products WHERE Order_ID = @Johns_Order_ID INSERT INTO Products (Order_ID,Product_ID) VALUES (@Johns_Order_ID,@Apple_ID) INSERT INTO Products (Order_ID,@Orange_ID) INSERT INTO Products (Order_ID,@Coconut_ID) INSERT INTO Products (Order_ID,@Banana_ID)
而不是简单地做这样的事情:
INSERT INTO Products_Table (Product_Name,@Banana_ID) INSERT INTO Products (Order_ID,@Banana_ID)
那么为什么NHibernate会删除Products表中的所有关联,以便在我只是尝试在其中插入新产品时再次重新创建它们?怎么避免呢?
提前致谢!
PS:我试图使用这个SO Question中建议的逆映射属性,但即使新产品被保存,它与订单的关联也没有.
编辑:
Order order = session.Load<Order>(orderId); order.Products.Add(new Product() { Name = "Banana" }); using (ITransaction transaction = session.BeginTransaction()) { session.Update(order); transaction.Commit(); }
解决方法
在SO:
NHibernate Many-To-Many Is Deleting All Associations Before Inserting上已经存在类似的问题
来自NHibernate的documentation:
Bags are the worst case. Since a bag permits duplicate element values and has no index column,no primary key may be defined. NHibernate has no way of distinguishing between duplicate rows. NHibernate resolves this problem by completely removing (in a single DELETE) and recreating the collection whenever it changes. This might be very inefficient.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。