NHibernate one-to-many mapping
I want to map one to many objects Person and PersonAddress
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 person object property in address. It creates cyclic references and don't necessary for my application.
mapping file is like following:
<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 Person with person address I am receiving exception. Because it tries to insert PersonAddress with invalid id (d开发者_JS百科efault -1, 0, etc).
in samples that I have found it is specified back reference from child to parent
Try this:
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 should have a reference to the Person, and not just a PersonId. And if you have difficulties with the .hbm.xml mapping files, consider using Fluent NHibernate instead. Its automatic mapping feature works like a charm.
There is also a video series on NHibernate, which covers the subject pretty well.
Just answered here
精彩评论