views:

1045

answers:

2

Hi,

If I have a collection mapped in Fluent NHibernate and I want to apply an order to that collection how do I do that?

Eg:

HasMany(x => x.PastDates)
            .AsBag().Cascade
            .SaveUpdate()
            .KeyColumnNames.Add("EventId")
            .Where(e => e.DateFrom < DateTime.Now.Date)
            .Inverse();

I'm looking for the equivalent of the order-by attribute in HBM files.

Thanks

+3  A: 

It appears that the "order-by" attribute is not in the FluentNHibernate API. I don't see an issue for it so this may be a conscious omission. You should be able to add it using SetAttribute but this user was unable to get it to work.

HasMany(x => x.PastDates)
        .AsBag().Cascade
        .SaveUpdate()
        .KeyColumnNames.Add("EventId")
        .Where(e => e.DateFrom < DateTime.Now.Date)
        .Inverse()
        .SetAttribute("order-by", "column_name");

Be aware that setting order-by may change the collection type that NHibernate uses; however this does not apply for bags.

Jamie Ide
Thanks for your help. Ill give that a try. Through posting this I spotted a glaring error also "< DateTime.Now.Date" really needs to be getDate().
madcapnmckay
This not a deliberate omission, FYI :)
James Gregory
Is there any way to sort in descending order this way?
JC Grubbs
@JC: Yes. The order-by attribute has the syntax "column_name asc|desc", so it's possible. Fluent NH has added OrderBy and I expect that it works the same. See http://knol.google.com/k/fabio-maulo/nhibernate-chapter-6/1nr4enxv3dpeq/9#6%282E%292%282E%29%28C2%29%28A0%29Mapping_a_Collection
Jamie Ide
+3  A: 

Fluent NHibernate now has an OrderBy method which you can use:

HasMany(x => x.PastDates)
        .AsBag().Cascade
        .SaveUpdate()
        .KeyColumnNames.Add("EventId")
        .Where(e => e.DateFrom < DateTime.Now.Date)
        .Inverse()
        .OrderBy( "order-by DESC" );
Kevin Berridge

related questions