mkelley33
mkelley33

Reputation: 5601

How can I relate 2 classes via NHibernate?

Let's say I have one class "User", and it "has" a property of type "Profile". How can I configure my mappings to generate the schema and create both tables in the database?

Upvotes: 2

Views: 125

Answers (3)

Jonathan Moffatt
Jonathan Moffatt

Reputation: 13457

As an aside, if you are not a great fan of scripting up hibernate mappings (which I'm not) then you have a couple of other options.

Castle ActiveRecord is one alternative - it's a layer on top of NHibernate which (among other things) lets you declare your relationships using attributes on your classes and properties.

And Fluent NHibernate is another - it lets you programmatically setup your classes and relationships.

Both are a great improvement over writing your mapping xml by hand!

Upvotes: 1

Matt Hinze
Matt Hinze

Reputation: 13679

<many-to-one/>

Upvotes: 1

Srikar Doddi
Srikar Doddi

Reputation: 15599

If you are asking about the mapping, you can use the join as shown below. note: you obviously have to add some additional attributes to suit your app.

   <?xml version="1.0" encoding="utf-8" ?>
   <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"    namespace="MyNamespace" assembly="MyAssembly"    default-lazy="true">  
   <class name="User" table="User">    
   <id name="Id" column="user_id" unsaved-value="0">      
   <generator class="native" />    
   </id>    
   <property name="Profile" column="profile" />  
   </class>
   </hibernate-mapping>

   <?xml version="1.0" encoding="utf-8" ?>
   <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"    namespace="MyNamespace" assembly="MyAssembly"    default-lazy="true">  
   <class name="Profile" table="Profile">    
   <id name="Id" column="profile_id" unsaved-value="0">      
   <generator class="native" />    
   </id>    
   <property name="Profile" column="profile" />    
   </class>
   </hibernate-mapping>

Upvotes: 0

Related Questions