R – Fetch child without primary key NHibernate

nhibernatenhibernate-collectionsnhibernate-mapping

I am trying to get a collection of objects into a parent object through mapping.

I have a parent object "ScoreCard" whose primary key is a guid (Id) and a child "Score" object whose primary key is a guid (Id). I want to select the child objects for the parent based on two fields that both objects have but I can't get it to work, here's the mapping

<bag name="ScoreCard">
  <key>
    <column name="HoleId"/>
    <column name="PlayerId"/>
  </key>
  <one-to-many class="Score" not-found="ignore"/>
</bag>

I didn't design the database but the ScoreCard object comes from a view that returns both column I need plus the evil guid. Whatever I've tried, NHibernate keeps throwing an exception about the foreign key not being the same as the primary key.

This seems to me to be the most simple requirement, get a collection of things given some criteria, why am I so stuck?

Thanks for your help, sorry for the bad example code (subliminal golf watching at relatives house).

Best Answer

Well, I found it eventually. The parent object is drawn from a view giving three columns and no key. I can map a composite key to the HoleId and PlayerId instead of the evil guid that I found when I looked at the code. This is great as I can easily map the Score objects I need and then lazy load them using NHibernateUtil.Initialize.

My mapping xml needs to look like this

<class name="ParentObject">
    <composite-id>
      <key-property name="HoleId" column="HoleId" />
      <key-property name="PlayerId" column="PlayerId" />      
    </composite-id>
    <property name="EvilGuid" column="Id" />
    <bag name="ScoreCard">
      <key>
        <column name="HoleId"/>
       <column name="PlayerId"/>
      </key>  
      <one-to-many class="Score" not-found="ignore"/>
    </bag>
</class>

I got my inspiration from this post, please also pay attention to Stefan's answer as I feel I had a lucky break here, and the design could be made better with more thought about DDD.

Thanks for your help.

Related Topic