3

请考虑以下映射代码:

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字段在映射中充当外键和复合键的一部分,BankBranchNHibernate 正确构建 DB,一切似乎都很好,直到我尝试在BankBranch表中插入记录。

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

我需要作为主键FinancialPeriodRefBankBranch一部分,而它绝对等于FinancialPeriodReffrom Bank

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

4

1 回答 1

5

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

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

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

于 2014-08-14T08:47:44.147 回答