使用QueryOver的多个子查询

时间:2013-01-17 18:46:45

标签: nhibernate queryover

我需要帮助将此sql查询转换为QueryOver Nhibernate标准。

select distinct * from event e where e.name like '%req%' 
or e.Id in (select r.eventId from requirement r where r.name like '%req%') 
or e.Id in (select r.eventId from requirement r where r.id 
in (select s.requirementId from solution s where s.name like '%sol%'))

var queryOver = session.QueryOver<Event>()
                       .Where(x => x.Name.IsInsensitiveLike("%"+searchTerms[1]+"%"))
                       .OrderBy(x => x.CreatedOn).Asc;

到目前为止,我有主要查询,但找不到有关如何添加子查询的足够参考资料。使用joinQueryOver没有成功。

事件具有一对多的rel和需求,并且需求具有一对多的rel with solution。

  Requirement reqAlias = null;
  Solution solAlias = null;

  var subQuery = QueryOver.Of<Event>()                                
      .JoinAlias(x => x.Requirements, () => reqAlias)
      .Where(x => x.Name.IsInsensitiveLike(searchTerms[2]))
      .JoinAlias(() => reqAlias.Solutions, () => solAlias)
      .Where(x => x.Name.IsInsensitiveLike(searchTerms[3]))
      .Select(Projections.Group<Event>(x => x.Id));

  var events = session.QueryOver<Event>()
      .Where(x => x.Name.IsInsensitiveLike(searchTerms[1]))
      .WithSubquery.WhereProperty(x => x.Id).In(subQuery)
      .List().ToList();

仍然无法正常工作。

1 个答案:

答案 0 :(得分:1)

使用IsInsensitiveLike NHibernate在解析后附加%,并使用lower进行小写比较。在您的代码中,您自己附加%,结果为

select distinct * from event e where e.name like %lower('%req%')%

反过来,它不起作用。

此外,您有3个子查询,没有大的子查询,因此您需要重新构建代码以解决此问题:

select r.eventId from requirement r where r.name like '%req%'

var firstQuery = QueryOver.Of<Requirement>()                                
                          .Where(r => r.Name.IsInsensitiveLike(searchTerms[2]))
                          .Select(r => r.EventId);

然后,

select s.requirementId from solution s where s.name like '%sol%'

var solutionQuery = QueryOver.Of<Solution>()                                
                           .Where(s => s.Name.IsInsensitiveLike(searchTerms[3]));

然后,

select r.eventId from requirement r where r.id 
in (select s.requirementId from solution s where s.name like '%sol%')

var requirementQuery = QueryOver.Of<Requirement>()
                                .WithSubquery
                                .WhereProperty(r => r.Id).In(solutionQuery)
                                .Select(r => r.EventId);

然后,您需要使用Restrictions.Or构建主查询以包含3个查询。