I'm trying to add projection to an NHibernate LINQ query (via .select()
), but since I have a bit of logic I want to use a helper class rather than returning a projected model directly.
My code looks like this (shortened):
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
is an object which transforms my MessageInstance
object into a MessageModel
and it contains logic to handle different scenarios, since it all depends on related entities.
This fails with error:
Field Dal.Repositories.MessageRepository._messageModelHelper' is not defined for type 'NHibernate.Linq.NhQueryable`1 [Domain.Entities.Message]'
If I avoid using a field (which is necessary for DI), and do this:
.Select(m => new MessageModelHelper().BuildMessageModel(m))
I simply get a System.NotSupportedException
.
It appears my approach won't work. What can I do, while avoiding the need to return new MessageModel
directly? Also I really need to keep projection, I can't operate on an enumerable.
You have to call the
BuildMessageModel()
"locally":Note that, as written, this won't do an SQL projection, so the full object will be selected from the DB.