Cascade insert on one-to-many with fluent NHibernate

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-08 06:27:49

问题


I have two classes mapped using fluent NHibernate - User and a UserRoleAssignment. An User has many UserRoleAssignments. Here's the relevant map for user:

HasMany(x => x.Roles)
.Table("UserRoleMap")
.Cascade.SaveUpdate();

And for UserRoleAssignment:

Map(x => x.User_Id);

As you can see, I'm only referencing from User to UserRoleAssignment. From UserRoleAssignment, I'm only mapping the foreign key column (User_Id). The problem is, that when I save the user, I get an exception caused by the foreign key constraint, because NHibernate is inserting 0 in the value for the User_id property. This only happens on new users - existing users (which already has an ID), works fine.

So the question is, how can I make sure that NHibernate sets the value of User_Id to the ID generated when inserting the new User?

Thanks a lot!


回答1:


This is documented in http://nhibernate.info/doc/nh/en/index.html#collections-onetomany:

Very Important Note: If the <key> column of a <one-to-many> association is declared NOT NULL, NHibernate may cause constraint violations when it creates or updates the association. To prevent this problem, you must use a bidirectional association with the many valued end (the set or bag) marked as inverse="true". See the discussion of bidirectional associations later in this chapter.



来源:https://stackoverflow.com/questions/3763824/cascade-insert-on-one-to-many-with-fluent-nhibernate

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