NHibernate QueryOver关联不包含项目

时间:2011-09-10 07:09:06

标签: nhibernate queryover

有人可以帮我将LINQ表达式翻译成Nhibernate QueryOver

from m in messages
where !m.Recipients.Any(rcpt => rcpt.IsDeleted && rcpt.User = user)

我试过这个

var qry = Session.QueryOver<UserMessage>();
qry.Where(m => m.Recipients.Any(r => !r.IsDeleted && r.User == user));

但得到了

System.Exception:无法识别的方法调用:System.Linq.Enumerable:Boolean任何[TSource](System.Collections.Generic.IEnumerable 1[TSource], System.Func 2 [TSource,System.Boolean]

3 个答案:

答案 0 :(得分:3)

!m.Recipients.Any(...)转换为“不存在”子查询。您将需要一些别名来将子查询与主查询相关联,并且子查询将需要进行投影以使NHibernate满意。

尝试这样的事情:

UserMessage messageAlias = null;
UserMessage recipientMessageAlias = null;

var subquery = QueryOver.Of<MessageRecipient>()
    .JoinAlias(x => x.Message, () => recipientMessageAlias)
    .Where(x => x.IsDeleted == true) // your criteria
    .Where(x => x.User.Id == userId)
    .Where(() => recipientMessageAlias.Id == messageAlias.Id) // correlated subquery
    .Select(x => x.Id); // projection

var query = session.QueryOver(() => messageAlias)
    .Where(Subqueries.WhereNotExists(subquery));

return query.List();

答案 1 :(得分:2)

我设法这样:

UserMessage messageAlias = null;

var qry = Session.QueryOver<UserMessage>(() => messageAlias);

UserMessageRecipient recipientAlias = null;

var deletedbyUser = QueryOver.Of(() => recipientAlias)
  .Select(x => x.Id)
  .Where( () => recipientAlias.Message.Id == messageAlias.Id
    && (recipientAlias.Recipient == query.User && recipientAlias.IsDeleted))
                .DetachedCriteria;
qry.Where(Subqueries.NotExists(deletedbyUser));

答案 2 :(得分:1)

尝试将Linq版本与session.Query&lt;&gt;一起使用而不是QueryOver

var qry = Session.Query<UserMessage>();
qry.Where(m => m.Recipients.Any(r => !r.IsDeleted && r.User == user));