NHibernate one-to-many foreign key is NULL

烈酒焚心 提交于 2019-12-13 20:22:24

问题


I have a problem with NHibernate. What i am trying to to is very simple: I have two Classes. UserTicket and UserData. A UsertTicket has some UserData and a UserData belongs to one UserTicket:

public class UserData{
    public virtual int Id { get; set; }
    public virtual String PDF_Path { get; set; }

}

public class UserTicket
{
    public virtual int Ticketnr { get; set; }
    public virtual IList<UserData> UserData { get; set; }
}

And here the mappig xml:

<class name="UserTicket" table="UserTicket">
<id name="Ticketnr">
  <generator class="identity"/>
</id>
 <bag name="UserData" inverse="true" cascade="all-delete-orphan" lazy="false">
  <key column="FK_Ticketnr" not-null="false"/>
  <one-to-many class="UserData" />
 </bag>
</class>




 <class name="UserData" table="UserData">
  <id name="Id">
    <generator class="identity"/>
  </id>
  <property name="PDF_Path" />
 </class>

When i run it, it works, but the column FK_Ticketnr in the DB-Table of UserData is always = NULL. Someone told me i have to make a back link from my Child (UserData) to the Parent-Class. But i can not figure out how to do so. How do i get Hibernate to write the value of the Primary-Key (Ticketnr) of UserTicket into FK_Ticketnr?

Thanks in advance


回答1:


Remove inverse="true" on your bag. That is telling NHibernate that the relationship is managed from the UserData mapping. Since you don't have a back reference, it is never persisted. The other option is to put a parent reference on UserData, but I wouldn't recommend it if you don't need it.




回答2:


The alternative is the following...

public class UserData
{
    // Keep your other properties, add this one too...
    public virtual UserTicket Ticket { get; set; }
}

Modify your mapping file like this...

<class name="UserData" table="UserData">
    <id name="Id">
        <generator class="identity" />
    </id>
    <property name="PDF_Path" />
    <many-to-one name="Ticket" column="FK_Ticketnr" />
</class>

Keep the inverse="true" on the bag.

If you go with this approach, you will need to set Ticket on your UserData objects when you add them to the UserData bag. In other words, you need to maintain both sides of the relationship. You could do this manually or you could try to automate it a little with with methods or constructors.



来源:https://stackoverflow.com/questions/4207758/nhibernate-one-to-many-foreign-key-is-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!