These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 posts ] 
Author Message
 Post subject: One-to-Many Relation (User, Role)
PostPosted: Fri Sep 10, 2010 12:30 pm 
Newbie

Joined: Fri Sep 10, 2010 12:20 pm
Posts: 3
Hi All,
I am new to NHibernate but relations are driving me crazy.

My simple database is user, role and function. Each user has a single role. Role and function are many-to-many.
So the database roughly looks like:
User: UserID (PK), Name, RoleID (FK)
Role: RoleID (PK), Name
Function: FunctionID (PK), Name
Role_Function: RoleID (PK), FunctionID (PK)

What should be my User, Role and Function mapping files (or a link to a tutorial that explains one-to-many, many-to-one and one-to-one relations)?

I have created the User class/mapping file with RoleID and it worked successfully. However when I change from RoleID to Role I cannot save any user because I got the exception "cannot insert null in User.RoleID"?

Thanks in advance,
Shehab.


Top
 Profile  
 
 Post subject: Re: One-to-Many Relation (User, Role)
PostPosted: Fri Sep 10, 2010 12:58 pm 
Newbie

Joined: Fri Sep 10, 2010 12:20 pm
Posts: 3
Hi All,
I found the answer. I was really desperate, that's why I posted here.
The following link http://sdesmedt.wordpress.com/2006/09/04/nhibernate-part-4-mapping-techniques-for-aggregation-one-to-many-mapping/ provides the answer.

In short, in the user.hbm.xml I added this line
Code:
<many-to-one name="Role" class="Role" column="RoleID"/>

and in the Role.hbm.xml I added these lines
Code:
<bag name="Users" lazy="true">
   <key column="RoleID"/>
   <one-to-many class="User"/>
</bag>


In User.cs I added
Code:
public virtual Role Role { get; set; }

and in Role.cs I added
Code:
public virtual IList<User> Users { get; set; }


Now when I create a User object and set its Role, it is saved in the database with the appropriate RoleID.

Again sorry for posting and answering myself but it was really depressing to spend a lot of hours on such a simple thing.

Best regards,
Shehab.


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.