NHibernate One-to-Many Mapping
I want to match one to many Person and PersonAddress objects
public class Person{
public virtual int Id {get; set;} public virtual string FirstName {get; set;}
public virtual ICollection<PersonAddress> PersonAddress { get; set; }}
public class PersonAddress{
public virtual int Id {get; set;}
public virtual int PersonId {get; set;}
... }
I don't want to have a property on the person object in the address. It creates circular references and is not needed for my application.
the mapping file looks like this:
<class name="Person" table="Persons" >
<id name="Id" type="Int32" column="PersonId">
<generator class="identity"/>
</id>
<set name="PersonAddress" table="PersonAddress" lazy="true" fetch="join" outer-join="true" cascade="all-delete-orphan">
<key column="PersonId"></key>
<one-to-many class="PersonAddress"/>
</set>
</class>
<class name="PersonAddress" table="PersonAddress" >
<id name="Id" type="Int32" column="Id">
<generator class="identity"/>
</id>
<property name="PersonId" column="PersonId" type="Int32"/>
<property name="PhoneWork" column="PhoneWork" type="String"/>
</class>
when trying to insert a person with a face address, I get an exception. As it is trying to insert PersonAddress with invalid ID (default -1, 0, etc.).
the samples I found have a backlink from child to parent
+2
a source to share
2 answers
Try the following:
public class Person {
public virtual int Id { get; set; }
public virtual string FirstName { get; set; }
public virtual IList<PersonAddress> PersonAddress { get; set; }
... }
public class PersonAddress {
public virtual int Id { get; set; }
public virtual Person Person { get; set; }
... }
You must have a reference to Person, not just PersonId. And if you're having trouble with the .hbm.xml mapping files, use Fluent NHibernate instead . Its auto display function works like a charm.
NHibernate also has a video that covers the topic pretty well.
+1
a source to share