views:

6234

answers:

1

I have a problem. Imagine this data model:

[Person] table has: PersonId, Name1
[Tag] table has: TagId, TagDescription
[PersonTag] has: PersonId, TagId, IsActive

Since [PersonTag] isn't just a simple many-to-many join table, i have all three entities created in nHibernate (exactly like they are in the data model). PersonTag, therefore, needs a composite-id, which I have mapped to a class like this:

<composite-id name="PersonTagKey" class="PersonTagKey">
  <key-property name="PersonId"></key-property>
  <key-property name="TagId"></key-property>
</composite-id>

I want to traverse the object graph and be able to look at both the Person and Tag objects from a retrieved PersonTag object. So, I have properties on the PersonTag object to do that, mapped like this:

<many-to-one name="Person" column="PersonId" lazy="proxy" cascade="none" class="Person"/>
<many-to-one name="Tag" column="TagId" lazy="proxy" cascade="none" class="Tag"/>

When I try to create a PersonTag object and save it, I get an "Invalid index n for this SqlParameterCollection with Count=n" error. I know this is because I've mapped the PersonId and TagId properties twice, once for the composite-id, and once for the many-to-one relationship. If I don't map the many-to-one objects, then everything works fine.

Is there some way for me to be able to have a composite-id AND a many-to-one relationship based on the same column modeled in the same nHibernate entity?

+6  A: 

Kay, here's the answer. Little-to-no documentation on this:

<composite-id name="PersonTagKey" class="PersonTagKey"> 
  <key-many-to-one name="Person" column="PersonId" lazy="proxy" class="Person">
  <key-many-to-one name="Tag" column="TagId" lazy="proxy" class="Tag"/>
</composite-id>

This will allow you to create a composite-id made up of the inverse of a many-to-one relationship.

Good hunting...

joshua.ewer
You're bang on about there being hardly any documentation on this! Could you clarify something for me a bit? What were the final class definitions like? are they class Person{ ISet<PersonTag> PersonTags; } class Tag { ISet<PersonTag> PersonTags; } class PersonTag { PersonTagKey Key; bool IsActive; } class PersonTagKey { Person Person; Tag Tag; }
mcintyre321
You got it! Only difference was that I was using List<T>, not ISet<T>. That end up working for you?
joshua.ewer