我最终将集合更改为使用列表而不是集合。然后我将以下函数添加到我的实体类中,它以正确的顺序插入新项目。
/// <summary>
/// Inserts inContract and maintains order by ContractId
/// Does not allow duplicates (assuming list is ordered)
/// </summary>
/// <param name="inContract">Contract to insert</param>
/// <returns>True if add was successful and false otherwise</returns>
public virtual bool AddContract(Contract inContract)
{
ContractComparer contractComparer = new ContractComparer();
for (int i = 0; i < myContracts.Count; i++)
{
int compareVal = contractComparer.Compare(inContract, myContracts[i]);
if (compareVal == 0)
{
return false;
}
//catches case where contract should be inserted at the end of the list
if (i == myContracts.Count - 1)
{
myContracts.Add(inContract);
return true;
}
if (compareVal > 0) continue;
myContracts.Insert(i, inContract);
return true;
}
return false;
}
Fluent 映射中的 OrderBy 确保从数据库中出来的列表是有序的。
HasMany(x => x.Contracts)
.Cascade.AllDeleteOrphan()
.OrderBy("CONTRACT_ID")
.KeyColumn("EV_PROJECT_LEDGER_KEY");
虽然这可行,但我确实喜欢通过传递自定义比较器类的 hbm.xml 映射文件允许的排序属性,因为它保持了顺序并且不允许重复。