How to add sort with custom comparer to Fluent nHibernate collection mapping
I need to rewrite the following collection mapping using Fluent nHibernate.
<set name="Contracts" sort="ContractComparer, ActualsModels" inverse="false" lazy="true" cascade="all">
<key column="EV_PROJECT_LEDGER_KEY"/>
<one-to-many class="Contract"/>
</set>
Specifically I don't know how to map the sort="ContractComparer, ActualsModels"
attribute with my custom comparer class. This is what I have so far:
HasMany(x => x.Contracts)
.Cascade.All()
.OrderBy("CONTRACT_ID")
.KeyColumn("EV_PROJECT_LEDGER_KEY");
OrderBy only sorts the data coming directly from the database, however I need to keep the collection sorted even after adding new elements. I can achieve this by using the .hbm mapping pasted above however I would like to move to using the Fluent mapping exclusively.
I ended up changing the collection to use a List rather than a Set. Then I added the following function to my entity class which inserts new items in the correct order.
/// <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;
}
The OrderBy in the Fluent mapping ensures that the list is ordered coming out of the database.
HasMany(x => x.Contracts)
.Cascade.AllDeleteOrphan()
.OrderBy("CONTRACT_ID")
.KeyColumn("EV_PROJECT_LEDGER_KEY");
While this works I did like the sort attribute allowed through the hbm.xml mapping file passing the custom comparer class because that maintained the order and did not allow duplicates.
链接地址: http://www.djcxy.com/p/39460.html