选择或选择列表:我想要包含整个实体

时间:2013-07-12 04:10:20

标签: nhibernate queryover

我正在查询对象列表,然后将它们与子查询相关联。

我想返回子查询的结果以及根实体。但是

我无法弄清楚如何实际返回根实体,我只能返回它的各个属性。

具体来说,这有效:

this.Session.QueryOver<MediaFile>(() => mediaFile)
            .SelectList(list => list.Select(mf => mf.Id));

但这不是:

this.Session.QueryOver<MediaFile>(() => mediaFile)
            .SelectList(list => list.Select(mf => mf));

我收到以下错误:

  

无法解析MediaFile的属性

有谁知道如何将实体作为列表中的属性包含在内?

以下是我的完整示例:

// My target class
private class MediaFileAndCount
{
    // I can successfully populate these fields.
    public long MediaFileId { get; set; }
    public int DistinctPlaylistCount { get;set; }

    // But I want to populate this field!
    public MediaFile MediaFile { get; set; }
}


private void TrySingleQuery()
{
    MediaFile mediaFile = null;
    PlaylistEntry playlistEntry = null;

    MediaFileAndCount mfc = null;
    var subQuery = QueryOver.Of<PlaylistEntry>(() => playlistEntry)
        .Where(() => playlistEntry.MediaFile.Id == mediaFile.Id)
        .Select(Projections.CountDistinct<PlaylistEntry>(p => p.Playlist));


    var query = this.Session.QueryOver<MediaFile>(() => mediaFile)
        .SelectList(list => list
            .Select(mf => mf.Id).WithAlias(() => mfc.MediaFileId)
            .Select(Projections.SubQuery(subQuery)).WithAlias(() => mfc.DistinctPlaylistCount)
     // .Select(mf => mf).WithAlias(() => mfc.MediaFile)  // This line fails
        )
        .TransformUsing(Transformers.AliasToBean<MediaFileAndCount>());


    var results = query.List<MediaFileAndCount>();
}

1 个答案:

答案 0 :(得分:3)

查询它的另一种方式

var allMediaFiles = session.QueryOver<MediaFile>().Where(...).ToFuture(); // just get the MediaFiles into sessionCache

var results = session.QueryOver<PlaylistEntry>()
    .Where(p => p.MediaFile...)
    .SelectList(list => list
        .GroupBy(p => p.MediaFile.Id)
        .CountDistinct(p => p.Playlist))
    .ToFuture<object[]>()
    .Select(a => new MediaFileAndCount
    {
        MediaFile = session.Get<MediaFile>((long)a[0]),
        DistinctPlaylistCount = (int)a[1]
    })
    .ToList();

foreach (var mediaFile in allMediaFiles.Except(results.Select(r => r.MediaFile)))
{
    results.Add(new MediaFileAndCount { MediaFile = mediaFile });
}