开发者

NHibernate one-to-many foreign key is NULL

开发者 https://www.devze.com 2023-01-26 02:55 出处:网络
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:

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="UserTi开发者_JS百科cket">
<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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号