仅从NHibernate子查询中选择某些属性

时间:2015-04-15 11:40:07

标签: c# linq nhibernate linq-to-nhibernate

所以我有一个像this的查询:

var sq = QueryOver.Of<Image>()
    .Where(i => i.NumID == ImageID) //The ImageID is for example 1026
    .Select(i => i.Album.Id);       // here we return the Album.ID (column AlbumID)

// just Albums with searched Image
var query = QueryOver.Of<Album>()
    .WithSubquery
    .WhereProperty(a => a.Id)
    .In(sq) 
    .List<Album>();

现在假设我的相册包含一个我并不总是想加载的大型属性,我只想加载相册ID和名称,所以我尝试了以下内容:

// just Albums with searched Image
var query = QueryOver.Of<Album>()
    .WithSubquery
    .WhereProperty(a => a.Id)
    .In(sq)
    .Select(x => new{x.Id, x.Name})
    .List<Album>();

但这会产生一个 System.InvalidOperationException variable 'x' of type 'Album' referenced from scope '', but it is not defined

.List 之后放置 .Select ,但是SQL会加载所有的Album,而这正是我想要避免的。

1 个答案:

答案 0 :(得分:2)

重点是使用NHibernate QueryOver方法SelectList,而不是LINQ Select方法

// .Select(x => new{x.Id, x.Name})
.SelectList(list => list
    .Select(x => x.Id)
    .Select(x => x.Name)
)

SelectList属于QueryOver世界,并将转换为投影

如果我们想得到Album的清单,我们甚至需要trasfromer

Album a = null;

...
.SelectList(list => list
    .Select(x => x.Id).WithAlias(() => a.Id)
    .Select(x => x.Name).WithAlias(() => a.Name)
)
.TransformUsing(NHibernate.Transform.Transformers.AliasToBean<Album>())