這是一個例子使用投影:
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