nhibernate - 选择或选择列表 : I Want to include the entire entity

标签 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));

我收到以下错误:

Could not resolve property : of 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>();
}

最佳答案

另一种查询方式

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 });
}

关于nhibernate - 选择或选择列表 : I Want to include the entire entity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17607328/

相关文章:

c# - 将值为 System.Guid.Empty 的 NHibernate "translate"C# POCO Guid 属性保存为数据库 uniqueidentifier 字段的 NULL?

c# - Nhibernate Group By 和 Alias To Bean

NHibernate 或存在

c# - NHibernate 3.2 QueryOver 按属性区分

NHibernate QueryOver 和 JoinQueryOver 选择所有列

c# - 通过连接查询动态获取

c# - NHibernate 中不区分大小写的排序顺序

nhibernate - Session.SetBatchSize 不会更改批量大小

c# - 在 UnitOfWork 和 Repository 之间共享一个 NHibernate session

c# - IStatelessSession 多对一插入对象