考慮下面的映射代碼,請:共享領域,如功能NHibernate複合鍵和外鍵
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.
這表明我已經映射一個字段(FinancialPeriodRef
)兩次FK和PK出現,我不知道如何解決問題。
我需要在BankBranch
中的FinancialPeriodRef
作爲主鍵的一部分,而它絕對等於從Bank
的FinancialPeriodRef
。
我需要這個字段來建立唯一的約束,組合鍵的好處也是必不可少的。
不確定究竟是什麼可能導致您的問題,但'BankBranchMapping'類映射可能不是你想要的。看看如何在這個[SO問題和接受的答案]中使用'KeyReference'方法(http://stackoverflow.com/questions/3997114/how-to-map-composite-id-with-fluent-nhibernate-using-的接口)。使用'KeyReference',你可以從地圖上刪除'References(...'),並且確保從屬類(例如'Bank'等)的Id生成設置正確 – 2013-02-21 15:13:00
我使用[KeyReference]代替但是問題仍然沒有解決,導致錯誤的主要原因是NHibernate無法理解爲什麼你要映射一個數據庫字段兩次,一次作爲ForeignKey,再次作爲Primarykey。 – 2013-02-27 07:14:18
我也有這個確切的問題 - 沒有你設法找到解決辦法?提前致謝:] – 2014-08-14 07:59:56