开发者

Fluent NHibernate Order by Property in related Entity

开发者 https://www.devze.com 2023-03-02 03:48 出处:网络
I have 2 tables in my database: CREATE TABLE [items]( [item_id] [int] IDENTITY(1,1) NOT NULL, [item_name] [varchar](50) NOT NULL,

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");
        }
    }

开发者_StackOverflow中文版

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.


You just need to add a join to your criteria.

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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消