在 NHibernate 中的一次保存操作中将实体列表添加到父实体
我正在使用 Fluent Nhibernate,我的相关实体是:
public class Product
{
public virtual int ID {get; set;}
public virtual string Name {get; set;}
public virtual Supplier Supplier {get; set;}
}
public class Supplier
{
public virtual int ID {get; set;}
public virtual string Name {get; set;}
public virtual List<Product> Products {get; set;}
}
在映射中,供应商在产品 + 逆 + 级联上有 HasMany。为了一次保存所有产品。 我的产品主键和相等成员是用 NH 序列生成的 Id。
我需要为新供应商创建产品列表。好吧,如果我在产品从数据库获取主键之前将它们添加到列表中,则只有第一个产品被添加到列表中,因为所有产品的 ID 都是 0,因此 equals 方法返回 true,并且列表“认为”它已经有那个产品了。
我可以在添加到供应商列表之前将产品一一保存,以便获得数据库的 Id 值。但这并没有使用级联能力。
任何有创意的建议都将受到欢迎。
I'm using Fluent Nhibernate and my relevant entities are:
public class Product
{
public virtual int ID {get; set;}
public virtual string Name {get; set;}
public virtual Supplier Supplier {get; set;}
}
public class Supplier
{
public virtual int ID {get; set;}
public virtual string Name {get; set;}
public virtual List<Product> Products {get; set;}
}
In the mapping the supplier has HasMany on the Products + Inverse + Cascade.All in order to save all the prodcuts at once.
My Product Primary Key and thus the equality members is the Id which is generated with NH sequence.
I need to create a list of products to a new supplier. Well if I add the products to the list before they get the primary key from the DB, only the first product being added to the list because the ID is 0 for all the products so the equals method return true, and the list "thinks" it already has that product.
I can save the products one by one before adding to the supplier list so the will get the Id value for the data base. But that doesn't use the cascade ability.
Any creative suggestion will be welcome.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
很明显,您通过 Id 进行盲目比较是故意破坏相等性。
我通常不覆盖实体中的
Equals
,因为它在某些不需要的情况下强制加载。如果你真的想覆盖 Equals,你可以这样做:
It's clear that you are intentionally breaking equality by doing a blind compare by Id.
I usually do not override
Equals
in my entities because it forces loading in some cases where it's not needed.If you really want to do override Equals, you can do something like:
我不知道我是否 100% 理解这个问题,但无论如何:
我们使用类似的方法,其中活动有一个注册列表。但是,正如您提到的,我们会在保存实际事件之前先保存注册。一次添加多个注册时,这会导致 N+1 问题,但在我们的场景中很少出现这种情况。如果我们使用另一个 id 生成器(例如 HiLo),也许这个问题就会消失?我不知道,因为我们还没有时间去调查。
当我们删除注册时,级联操作会成功运行,并且事件的注册集合会正确更新。
I dont know if I understood the question 100%, but anyhow:
We use a similiar approach where an Event has a list of Registrations. We do however, as you mentioned, save the registrations first before saving the actual event. This causes the N+1 problem when adding many registrations at once, but thats rarely the case for our scenario. Maybe that problem would go away if we used another id-generator such as HiLo? I dont know because we havent had the time to look into it.
When we delete a registration the cascade operation works successfully, and the registration collection of the event is properly updated.