我知道如何将类类型分配给从单个表中检索的数据,如下所示:
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("");
}
答案 0 :(得分: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...