简体   繁体   中英

Fetch child without primary key NHibernate

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).

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.

The problem is this: NHibernate works best (but not only) for DDD, this means for creating domain classes first and make the database best fitting the domain model.

You have a composite-id relation to non-primary-key fields. So start praying that NHibernate can cope with that. Both composite-ids and relations by non-primary-keys are supported - for legacy databases - and generally discouraged for DDD.

I think the combination of both does not work. See this issue on NHibernates issue tracker: https://nhibernate.jira.com/browse/NH-1722 . You can vote for the feature there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM