一千萬個為什麽

搜索

在NHibernate中對子對象進行排序

我有一個加載一系列產品的方法。每個訂單都有一個名為Manufacturer的子對象(我在映射文件中設置了多對一關系)。我想按Products.Manufacturer.Name排序產品的集合。我怎樣才能做到這一點?

產品映射:

<?xml version="1.0" encoding="utf-8" ?>

  
    
      
    
    
    
    
    
   

制造商映射:

<?xml version="1.0" encoding="utf-8" ?>

  
    
      
    
    
  

調用代碼:

public IList GetProducts(int startIndex, int rowCount, string sort, string productNameFilter, int? manufacturerIDFilter)
{
    IList result = null;

    using (ITransaction transaction = this.Session.BeginTransaction())
    {
        ICriteria query = this.Session.CreateCriteria();

        //Add paging...
        query.SetFirstResult(startIndex).SetMaxResults(rowCount);

        //Add filters...
        if (productNameFilter != null)
        {
            query.Add(Expression.Like("Name", productNameFilter, MatchMode.Anywhere));
        }
        if (manufacturerIDFilter.HasValue == true)
        {
            //This works when using Manufacturer.ID...
            query.Add(Expression.Eq("Manufacturer.ID", manufacturerIDFilter.Value));
        }


        //Add sort...
        switch (sort)
        {
            case "ProductName ASC":
                query.AddOrder(new Order("Name", true));
                break;
            case "ManufacturerName ASC":
                //This doesn't work when using Manufacturer.Name, but does when using Manufacturer.ID...
                query.AddOrder(new Order("Manufacturer.Name", true));
                break;
            case "ProductName DESC":
                query.AddOrder(new Order("Name", false));
                break;
            case "ManufacturerName DESC":
                query.AddOrder(new Order("Manufacturer.Name", false));
                break;
        }

        result = query.List();

        transaction.Commit();
    }

    return result;
}

最佳答案

我認為你需要使用類似下面的內容。

IList orders = Session.CreateCriteria(typeof(Order))
  .AddOrder(Order.Asc("Order.Customer.LastName")
  .List();

轉載註明原文: 在NHibernate中對子對象進行排序