1
votes

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

1 Answers

1
votes

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.