NHibernate two columns as composite key AND foreign keys at the same time

人盡茶涼 提交于 2019-12-10 10:26:34

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/7996817/nhibernate-two-columns-as-composite-key-and-foreign-keys-at-the-same-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!