【问题标题】:Fluent NHibernate HQL Assigning multiple class types to multiple table select queryFluent NHibernate HQL 将多个类类型分配给多个表选择查询
【发布时间】:2011-04-06 13:15:22
【问题描述】:

我知道如何将类类型分配给从单个表中检索到的数据,如下所示:

HQL 查询:

select s from Employee e join e.Store s where s.Id = 1

代码:

var stores = session.CreateQuery(hql).List<Store>();

foreach (var store in stores)
{
    Console.WriteLine(store.Name);

    foreach (var product in store.Products)
    {
        Console.WriteLine("    " + product.Name);
    }
}

但是我们如何将多个类类型分配给多个表连接查询呢?目前我无法指定任何类类型,因为数据来自多个表。

HQL 查询:

select distinct s.Name,p.Name,p.Price,p.Location.Aisle,p.Location.Shelf from Store s join s.Products p where s.Id = 1

代码:

var rows = session.CreateQuery(hql).List(); // Using List() instead of List<T>()

for (int i = 0; i < rows.Count; i++)
{
    IList cols = (IList)rows[i];

    for (int j = 0; j < cols.Count; j++)
    {
        Console.Write(cols[j] + " ");
    }

    Console.WriteLine("");
}

【问题讨论】:

    标签: nhibernate select hql fluent


    【解决方案1】:

    您需要指定一个转换器。一种选择是指定一个 EntityMap 转换器。

    session.CreateQuery.SetTransformer(Transformers.AliasToEntityMap)
    

    这将返回一个字典列表,其中包含基于您的查询的名称值对。或者,您可以创建一个映射到您的查询的 POCO 对象

    public class MyProjection
    {
       public string SName { get; set; }
       public string PName { get; set; }
       public float Price { get; set; }
       public string Aisle { get; set; }
       public string Shelf { get; set; }
    }
    

    然后指定一个不同的转换器

    session.CreateQuery.SetTransformer(Transformers.AliasToBean<MyProjection>())
          .List<MyProjection>();
    

    请记住,您需要为这两种方法指定别名

    select distinct s.Name as SName,p.Name as PName,p.Price as Price,
         p.Location.Aisle as Aisle, p.Location.Shelf as Shelf...
    

    【讨论】:

      猜你喜欢
      • 2010-12-09
      • 1970-01-01
      • 2012-03-07
      • 1970-01-01
      • 1970-01-01
      • 2012-06-30
      • 2011-02-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多