使用helper类的NHibernate LINQ投影

时间:2015-06-19 09:23:22

标签: c# linq nhibernate nhibernate-projections

我正在尝试将投影添加到NHibernate LINQ查询(通过.select()),但由于我有一些逻辑,我想使用辅助类而不是直接返回投影模型。

我的代码看起来像这样(缩短了):

var query = Session.Query<MessageInstance>();
... (a few .Fetch and .ThenFetch calls)
var result = query.Where(specification.IsSatisfiedBy())
                  .OrderBy(m => m.CreationDate)
                  .Select(m => _messageModelHelper.BuildMessageModel(m));

_messageModelHelper是一个将MessageInstance对象转换为MessageModel的对象,它包含处理不同场景的逻辑,因为它全部依赖于相关实体。

此操作失败并显示错误:

  

字段Dal.Repositories.MessageRepository._messageModelHelper'未定义类型'NHibernate.Linq.NhQueryable`1 [Domain.Entities.Message]'

如果我避免使用字段(这是DI所必需的),并执行此操作:

.Select(m => new MessageModelHelper().BuildMessageModel(m))

我只是得到System.NotSupportedException

看来我的方法不起作用。我可以做什么,同时避免直接返回new MessageModel?另外我真的需要保持投影,我无法对可枚举进行操作。

1 个答案:

答案 0 :(得分:0)

您必须在本地拨打BuildMessageModel()“:

var result = query.Where(specification.IsSatisfiedBy())
                  .OrderBy(m => m.CreationDate)
                  .AsEnumerable() // From this point onward the query
                                  // will be executed C#-side
                  .Select(m => _messageModelHelper.BuildMessageModel(m));

请注意,如上所述,这不会进行SQL投影,因此将从数据库中选择完整对象。