级联插入一对多与流利的NHibernate [英] Cascade insert on one-to-many with fluent NHibernate
问题描述
HasMany(x => x.Roles)
.Table(UserRoleMap )
.Cascade.SaveUpdate();
而对于UserRoleAssignment:
Map(x => x.User_Id);
正如您所看到的,我只是从User到UserRoleAssignment引用。从UserRoleAssignment,我只映射外键列(User_Id)。
问题是,当我保存用户时,由于外键约束导致异常,因为NHibernate在User_id属性的值中插入0。这只发生在新用户 - 现有的用户(已经有一个ID),工作正常。
所以问题是,我怎样才能确保NHibernate设置值User_Id添加到插入新用户时生成的ID?
非常感谢!
这在 http:// nhibernate中有记录。 info / doc / nh / en / index.html#collections-onetomany :
lockquote
非常重要注意: / em>如果< one-to-many>
关联的< key>
code> NOT NULL ,NHibernate在创建或更新关联时可能会导致约束违规。为了避免这个问题,你必须使用一个双向关联来标记 inverse =true
。请参阅本章稍后讨论的双向关联。
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!
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 declaredNOT 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 asinverse="true"
. See the discussion of bidirectional associations later in this chapter.
这篇关于级联插入一对多与流利的NHibernate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!