我想查询一个nhibernate映射类,但结果应该是一个未映射的对象。映射和未映射的类如下所示:
[Class(NameType = typeof(ClassA)]
public class ClassA
{
[Cache(0, Usage = CacheUsage.ReadWrite)]
[Id(1, Name = "Id", UnsavedValue = null)]
[Generator(2, Class = "native")]
public virtual long? Id { get; set; }
[Property]
public virtual string PropertyA { get; set; }
[Property]
public virtual string PropertyB { get; set; }
}
public class ClassB
{
public string PropertyA { get; set; }
public string PropertyB { get; set; }
public int Number { get; set; }
}
我使用这种方法得到我想要的结果:
public ICollection<ClassB> Group()
{
var result =
Session.CreateCriteria(typeof(ClassA)).SetProjection(
Projections.ProjectionList().Add(Projections.RowCount(), "Number")
.Add(Projections.GroupProperty("PropertyA"))
.Add(Projections.GroupProperty("PropertyB")));
return
(result.List().Cast<IList>().Select(
entry =>
new ClassB {
Number = (int)entry[0],
PropertyA = (string)entry[1],
PropertyB = (string)entry[2]
}
)).ToList();
}
这样可以正常工作,但使用criteria-api?
是不是有更直接的方法答案 0 :(得分:7)
是的,只需做
result.SetResultTransformer(Transformers.AliasToBean<ClassB>());
result.List<ClassB>();
您还需要将属性投影包装为别名
Projections.Alias(Projections.GroupProperty("PropertyA"), "PropertyA")