【问题标题】:Sharing field as composite key and foreign key in Fluent NHibernate在 Fluent NHibernate 中将字段共享为复合键和外键
【发布时间】:2013-02-21 11:01:05
【问题描述】:

请考虑以下映射代码:

public sealed class BankMapping : ClassMap<Bank>
{
    public BankMapping()
    {
        CompositeId()
            .KeyProperty(x => x.SerialNumber, "SerialBankRef")
            .KeyProperty(x => x.FinancialPeriodId, "FinancialPeriodRef");
        Map(x => x.Code);
        Map(x => x.Title);
        Map(x => x.Comment);
        Map(x => x.IsActive);            
        HasMany(x => x.BankBranchs).KeyColumns.Add(new[] { "SerialBankRef", "FinancialPeriodRef" });

    }
}

BankBranch的映射代码是:

public sealed class BankBranchMapping : ClassMap<BankBranch>
{
    public BankBranchMapping()
    {
       CompositeId()
            .KeyProperty(x => x.FinancialPeriodId, "FinancialPeriodRef")
            .KeyProperty(x => x.SerialNumber, "SerialNumber");
        Map(x => x.Code);
        Map(x => x.Title);
        Map(x => x.Comment);
        Map(x => x.IsActive);
        Map(x => x.Address);
        Map(x => x.Fax);
        Map(x => x.Telephone);
        References(x => x.Bank).Columns(new[] { "SerialBankRef", "FinancialPeriodRef" });
    }
}

如您所见,FinancialPeriodRef 字段在 BankBranch 映射中充当外键和复合键的一部分,NHibernate 正确构建数据库,一切似乎都很好,直到我尝试在 BankBranch 中插入记录桌子。

错误System.IndexOutOfRangeException : Invalid index 10 for this SqlParameterCollection with Count=10. 表示我在出现 FK 和 PK 时两次映射了一个字段 (FinancialPeriodRef),但我不知道如何解决该问题。

我需要BankBranch 中的FinancialPeriodRef 作为主键的一部分,而它绝对等于来自BankFinancialPeriodRef

我需要这个字段来建立唯一约束,并且复合键的好处是必不可少的。

【问题讨论】:

  • 不确定究竟是什么导致了您的问题,但 BankBranchMapping 类映射可能不是您想要的。看看这个SO question & accepted answer是如何使用KeyReference方法的。使用KeyReference,您可以从地图中删除References(...。此外,请确保依赖类(例如Bank 等)的 Id 生成设置正确。
  • 我使用了 [KeyReference] 而不是 Reference 但问题仍然没有解决。错误的主要原因是 NHibernate 无法理解为什么要映射一个 DB 字段两次。一次作为外键,再次作为主键。
  • 我也遇到了这个确切的问题-您设法找到解决方案吗?提前致谢:]

标签: nhibernate fluent-nhibernate-mapping


【解决方案1】:

您需要使用 KeyReference 而不是 KeyProperty 来描述复合外键。

public BankBranchMapping()
{
    CompositeId()
        .KeyReference(x => x.FinancialPeriodId, "FinancialPeriodRef")
        .KeyReference(x => x.SerialNumber, "SerialNumber");
    ...
}

我遇到了和你完全相同的问题,大约一个小时后,我看到了这篇文章:https://stackoverflow.com/a/7997225/569662,它指出了我的正确。

【讨论】:

    猜你喜欢
    • 2018-11-07
    • 2014-05-26
    • 2011-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-26
    相关资源
    最近更新 更多