这是一个例子使用投影:
List results = session.CreateCriteria<BrandTable>()
.SetProjection(Projections.ProjectionList()
.Add(Projections.Id(), "Id")
.Add(Projections.Property("Name"), "Name")
)
.SetResultTransformer(Transformers.AliasToBean<BrandTable>()); // edit - don't forget the result transformer!
.List();
此处作为一例使用QueryOver:
NHibernate QueryOver select entity and aggregates
[编辑] 也,目前高速缓存的ICriteria时的错误预测。 (如果您尝试缓存查询,你会得到一个例外) https://nhibernate.jira.com/browse/NH-1090 [/编辑]
Releted帖子:
NHibernate Criteria: howto exclude certain mapped properties/collections?
Only retrieve specific columns when using Critera queries?
LINQ-NHibernate - Selecting only a few fields (including a Collection) for a complex object
,使您的查询重构安全的(没有“魔法字符串”),可以实现像这样:
public static class ObjectExtensions
{
public static string NameOf<T>(this T target, Expression<Func<T, object>> propertyExpression)
{
MemberExpression body = null;
if (propertyExpression.Body is UnaryExpression)
{
var unary = propertyExpression.Body as UnaryExpression;
if (unary.Operand is MemberExpression)
body = unary.Operand as MemberExpression;
}
else if (propertyExpression.Body is MemberExpression)
{
body = propertyExpression.Body as MemberExpression;
}
if (body == null)
throw new ArgumentException("'propertyExpression' should be a member expression");
// Extract the right part (after "=>")
var vmExpression = body.Expression as ConstantExpression;
// Extract the name of the property
return body.Member.Name;
}
}
使用这样的:
MyEntity entity = null; // don't need a 'valid' instance.
string propName = entity.NameOf(x => x.SomePropertyName);
您正在订购并在内存中应用投影,这就是为什么不起作用(.List()方法选择所有记录 – Vasea