NHibernate: Using Fluent Nhibernate to save child objects

家住魔仙堡 提交于 2019-12-02 19:10:17

I had this exact problem with fluent nhibernate. There appears to be a small bug in mapping one-to-many relationships and the relationships not automatically saving or cascading. See here for a posting about it on the Fluent NHibernate group.

Apparently, there is someone working on the issue!

I can;t say for sure that this is the issue with your code but it looks very similar to a problem I had. Hope that helps some!

Why did you include .Cascade.SaveUpdate() in the line

References(x => x.Cart, "ShoppingCartId").Cascade.SaveUpdate()

?

Perhaps it confuses NHibernate (or Fluent NHibernate) that there seems to be cascading saves/updates from both ends of your relation?

Configuring your HasMany to cascade ought to be sufficient to achieve what you want.

Try wrapping Session.SaveOrUpdate in a transaction, or force a flush directly after.

I'm not sure, but I don't think that NHibernate cascades the saving of objects to child objects. You don't show the code that calls SaveOrUpdate, but I know if you loop through the ShoppingCartItems at that point, saving each individually then they'll be persisted too.

I know nothing about NHibernate (The OPF I use does this for me), but isn't it the case that when you save the aggregate root (ShoppingCart) that code should also commit its compositely owned instances to the session too?

Is it possible that your cart items are saving first, then the cart? hence the child items have no parent ID to use?

You MAY need to explicitly save the cart back to the DB on create, then add the items into it and save - just to get the ID.

As noticed, you defined (in the database schema) fields with Identity, therefore, these fields must be set in the Map file. Example as the following:

Id(x => x.ID, "ShoppingCartItemId").GeneratedBy.Identity();

the error you are getting because you didn't set the Identity fields in the mapping to be generated by Identity, thus, when you are trying to Save(), the Identity column is not generated(and set to not null in the database) then it gives you the error.

The problem is with your configuration statement of sessionfactory. Don't use Exposeconfiguration if u want your data to persist. That will surely solve your problem of data persistence.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!