Search code examples
nhibernatenhibernate-mappingnhibernate-mapping-by-code

By code mapping of many-to-many with OrderBy


I'm using by code mappings and trying to map a manytomany. This works fine but I need OrderBy for the child collection items. I noticed this has been omitted (it does exist in the HBM mappings). e.g.

    public class Mapping : EntityMapper<Category>
    {
        public Mapping()
        {
            Set(x => x.Items, m =>
            {
                m.Table("ItemCategories");
                m.Key(k => k.Column("CategoryId"));
                m.Inverse(true);
                m.Cascade(Cascade.None);
            }, col => col.ManyToMany(m =>
            {
                m.Columns(x => x.Name("ItemId"));
                //m.OrderBy("Score desc"); // missing in Nh4.x?
            }));
        }
    }

Is there a workaround for this? I tried following the suggestion in this article whereby I can set the property before the session factory is built but it has no effect. e.g.

    cfg.GetCollectionMapping(typeof(Category).FullName + ".Items").ManyToManyOrdering = "Score desc";
    cfg.BuildSessionFactory();

Am I doing something wrong or is OrderBy on manytomany not supported in Nh4?

Also, is it possible to restrict the maximum number of items retrieved in the collection?


Solution

  • Replaced the many to many with one to many and introduced an entity that represents the relationship (followed advice from this article). This has the upside of allowing you to map the order-by column as well as other columns, and also solved the issue of restricting the number of items in the collection by using the one-to-many's Where() and Filter() clauses.