Reputation: 7448
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)?
Upvotes: 3
Views: 4511
Reputation: 15303
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.
Upvotes: 5