简体   繁体   English

NHibernate两列同时作为复合键和外键

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

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. 现在我找不到如何使用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. 虽然这个任务在EF Code First上是微不足道的,但是在这个项目上我被困在Net 3.5上并且不能使用它,所以NHibernate是唯一的另一个选择。

I tried using CompositeId(), References() and other stuff, tried various combinations but none did work. 我尝试使用CompositeId(),References()和其他东西,尝试了各种组合,但没有一个工作。 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)? 任何人都知道如何使用Fluent Nhibernate(没有xml配置)映射这个?

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 ): 如果您的ProductCategory实体中有实际的ProductCategory实体,那么您的映射应该看起来像这样(这里的关键是KeyReference而不是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: 如果您的ProductCategory只有Ids,它将如下所示:

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. 第一个代码示例中的KeyReferences指示外键关系。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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