Fluent NHibernate Order by Property in related Ent

2019-08-05 06:29发布

问题:

I have 2 tables in my database:

CREATE TABLE [items](
    [item_id] [int] IDENTITY(1,1) NOT NULL,
    [item_name] [varchar](50) NOT NULL,
    [group_id] [int] NOT NULL   
)

CREATE TABLE [itemgroup](
    [group_id] [int] IDENTITY(1,1) NOT NULL,
    [group_name] [varchar](50) NULL 
)

and here are mapping classes for these entities:

    public class ItemMap : ClassMap<Item>
    {
        public ItemMap()
        {
            Table("items");
            Id(x => x.Id).Column("item_id");
            Map(x => x.Name).Column("item_name");
            References(x => x.ItemGroup).Column("group_id").Fetch.Join();            
        }
    }
    public class ItemGroupMap : ClassMap<ItemGroup>
    {
        public ItemGroupMap()
        {
            Table("itemgroup");
            Id(x => x.Id).Column("group_id");
            Map(x => x.Name).Column("group_name");
        }
    }



How can I get all items from the database ordered by group name?

Just in case I'm using Fluent NHibernate v1.2.0.712.

回答1:

You just need to add a join to your criteria.

var criteria = Session.CreateCriteria<Item>()
                      .CreateAlias("ItemGroup", "group")
                      .AddOrder(Order.Asc("group.Name"));


回答2:

in your ItemGroup you must have a list of Item, suppose you call it Items

Then in ItemGroupMap add

mapping.HasMany(x => x.Items)
            .Cascade.All()
            .Inverse()
            .SetAttribute("order-by", "item_name");

Now you can have a list of ItemGroup with all children ordered by item_name