3

我想从我的数据层返回一个 DTO,它还包含子集合......例如:

Audio
 - Title
 - Description
 - Filename
 - Tags
     -  TagName
 - Comments
     -  PersonName
     -  CommentText

到目前为止,这是一个基本查询,但我不确定如何将子集合从我的实体转换为 DTO。

var query = Session.CreateCriteria<Audio>("audio")
            .SetProjection(
                Projections.ProjectionList()
                    .Add(Projections.Property<Audio>(x => x.Title))
                    .Add(Projections.Property<Audio>(x => x.Description))
                    .Add(Projections.Property<Audio>(x => x.Filename))
            ).SetResultTransformer(new AliasToBeanResultTransformer(typeof(AudioDto)))
            .List<AudioDto>();

这甚至可能吗,还是有另一种推荐的方法?

更新:只想添加一些关于我的场景的更多信息......我想将音频项目列表返回给当前登录的用户以及一些相关的实体,如标签、评论等......这些都相当简单使用多查询/未来。

但是,在向用户显示音频项目时,我还想向用户显示 3 个其他选项:

  • 天气他们已将此音频项目添加到他们的收藏夹列表中
  • 天气他们给这个音频“竖起大拇指”
  • 天气登录用户正在“关注”此音频的所有者
Favourites : Audio -> HasMany -> AudioUserFavourites

Thumbs Up : Audio -> HasManyToMany -> UserAccount

Following Owner : Audio -> References -> UserAccount ->

多对多 -> 用户帐户

希望这是有道理的...如果不是,我会尝试再次解释...我如何急切地为每个返回的音频实体加载这些额外的详细信息...我还需要 20 页中的所有这些信息。

我查看了批量获取,但这似乎为每个音频实体获取了所有的赞,而不是检查是否只有登录的用户赞了它。

很抱歉漫无边际:-)

保罗

4

1 回答 1

2

如果您想获取Audio包含Tags集合和Comments集合的对象,请查看 Aydende Rahien 的博客:http ://ayende.com/blog/4367/eagerly-loading-entity-associations-efficiently-with-nhibernate 。

You don't need to use DTOs for this; you can get back a list of Audio with its collections even if the collections are lazily loaded by default. You would create two future queries; the first will fetch Audio joined to Tags, and the second will fetch Audio joined to Comments. It works because by the time the second query result is being processed, the session cache already has the Audio objects in it; NHibernate grabs the Audio from the cache instead of rehydrating it, and then fills in the second collection.

You don't need to use future queries for this; it still works if you just execute the two queries sequentially, but using futures will result in just one round trip to the database, making it faster.

于 2011-06-15T16:09:01.133 回答