3

First of all, I've searched thoroughly online and here, without finding a clear solution to the task at hand. My apologies if my search wasn't accurate enough and this answer has already been posted.

The issue: I have a table. This table must have a primary key on two fields, and other fields containing some data. The two fields that are primary key must also be foreign keys, each on a different table. Something like (pseudo code ahead):

Product: Id (pk)
Category: Id (pk)

ProductCategory: (ProductId (fk on product), CategoryId (fk on category))(pk), SomeOtherField1, SomeOtherField2, etc

Now I can't find how to configure this using Fluent Nhibernate. While this task is trivial on EF Code First, on this project I'm stuck on Net 3.5 and can't use that, so NHibernate was the only other choice.

I tried using CompositeId(), References() and other stuff, tried various combinations but none did work. I don't think the errors I got are relevant, I just need a sample working configuration for a scenario like this.

Anyone does know how to map this using Fluent Nhibernate (no xml config)?

Matteo Mosca
  • 7,380
  • 4
  • 44
  • 80

1 Answers1

5

If you have actual Product and Category entities in your ProductCategory entity then your mapping should look something like this (the key here is KeyReference not KeyProperty):

CompositeId()
    .KeyReference(x => x.Product, "ProductId")
    .KeyReference(x => x.Category, "CategoryId");

Map(x => x.SomeOtherField1);

If you only have the Ids in your ProductCategory it would look something like this:

CompositeId()
    .KeyProperty(x => x.ProductId, "ProductId")
    .KeyProperty(x => x.CategoryId, "CategoryId");

Map(x => x.SomeOtherField1);

The KeyReferences in the 1st code sample indicate the foreign key relationships.

Cole W
  • 15,123
  • 6
  • 51
  • 85
  • It was indeed this. I had to use those KeyReference AND remove the "HasMany" from the other 2 entities, because it was creating duplicate FKs on both ends. Now it's really pretty. Thanks. – Matteo Mosca Nov 03 '11 at 15:10
  • What to do (other than fix the bad design) if ProductId happens to not be the primary key of Product? – Joel Christophel Mar 09 '20 at 18:38