我正在尝试对每个Products
生成的Manufacturer
的数量进行简单查询,但NHibernate不会生成MS SQL Server发现的有效的T-SQL。 / p>
session.Query<Product>()
.GroupBy(p => p.Manufacturer)
.Select(grp => new {Mftr = grp.Key.Name, ProductCount = grp.Count()})
.ToList();
这似乎很简单,但NHibernate生成的SQL语句不包含所有必需的列名,因此在针对SQL Server 2008或SQL Server CE数据库运行时失败。如果我将相同的代码指向内存中的SQLite数据库,它可以正常工作。
更多信息如下,我还创建了small console application that demonstrates my problem。 如何解决此问题?
select manufactur1_.Id,
cast(count(*) as INT),
manufactur1_.Id,
manufactur1_.Name
from "Product" product0_
left outer join "Manufacturer" manufactur1_
on product0_.Manufacturer_id=manufactur1_.Id
group by manufactur1_.Id -- Where's manufactur1_.Name?
public class Product {
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual Manufacturer Manufacturer { get; set; }
}
public class Manufacturer {
public virtual int Id { get; set; }
public virtual string Name { get; set; }
}
public class ProductMap : ClassMap<Product> {
public ProductMap() {
Id(x => x.Id).GeneratedBy.HiLo("1");
Map(x => x.Name);
References(x => x.Manufacturer).Cascade.SaveUpdate().Not.Nullable();
}
}
public class ManufacturerMap : ClassMap<Manufacturer> {
public ManufacturerMap() {
Id(x => x.Id) .GeneratedBy.HiLo("1");
Map(x => x.Name);
}
}
答案 0 :(得分:2)
这是一个QueryOver版本......
//alias variables
Manufacturer m = null;
ManufacturerProducts dto = null;
var result = Session.QueryOver<Product>
.Left.JoinAlias(x => x.Manufacturer, () => m)
.SelectList(list => list
.SelectGroup(() => m.Id).WithAlias(() => dto.Id)
.SelectGroup(() => m.Name).WithAlias(() => dto.Name)
.SelectCount(x => x.Id).WithAlias(() => dto.ProductCount))
.TransformUsing(Transformers.AliasToBean<ManufacturerProducts>())
.List<ManufacturerProducts>();