[英]NHibernate one-to-many mapping
I want to map one to many objects Person and PersonAddress 我想将一个对象映射到许多对象Person和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. 我不想在地址中包含person对象属性。 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 (default -1, 0, etc).
因为它尝试插入具有无效ID(默认为-1、0等)的PersonAddress。
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. 您应该引用Person,而不仅仅是PersonId。 And if you have difficulties with the .hbm.xml mapping files, consider using Fluent NHibernate instead.
并且,如果您对.hbm.xml映射文件有困难,请考虑改用Fluent NHibernate 。 Its automatic mapping feature works like a charm.
它的自动映射功能就像一个魅力。
There is also a video series on NHibernate, which covers the subject pretty well. 还有关于NHibernate的视频系列 ,涵盖了该主题。
刚刚在这里回答
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.