Nhibernate Queryover with subquery获取下一个免费号码

时间:2014-05-30 11:14:43

标签: nhibernate queryover

如何使用queryover在nHibernate中执行此操作:

SELECT MIN(t.subid)+1 AS NextID 
FROM subject t  
WHERE NOT EXISTS  
    (SELECT id FROM subject n WHERE n.subid=t.subid+1)

目前我有这个但由于这句话"SubId+1"

而无效
 _session.QueryOver(() => subject)
 .WithSubquery
 .WhereNotExists(
       subject 
       .Where(x => x.SubId==SubId+1)
       .Select(x => x.Id)
     )                                                         
 .Select(Projections.ProjectionList()
                     .Add(Projections.Min<subject>(x => x.SubId)))
 .List().First()                                     

1 个答案:

答案 0 :(得分:0)

一种方法,使用NOT IN代替NOT EXISTS(结果相同)就像这个(SQL查询会有所不同,但结果会相同)

Subjectsubject = null;
Subjectinner = null;
var subquery = QueryOver.Of<Subject>(() => inner)
    .Select(Projections.SqlProjection(
       // important the subid is the column name, not property name
       " subid - 1 as innerId" // the trick here is, that we compare 
       , new[] { "innerId" }       // inner ID - 1, with outer ID
       , new IType[] { NHibernateUtil.Int32 }))
    ;

var id = session.QueryOver(() => subject)
    .WithSubquery
      .WhereProperty(() => subject.ID)
      .NotIn(subquery)
    .Select(Projections.ProjectionList().Add(Projections.Min<Subject>(s => s.ID)))
    .SingleOrDefault<int>();

var id = id + 1 ; // here we increment in C#, instead of projecting that into SQL

总结:不确定您使用的算法,但是如何获得&#34; subid - 1&#34;是使用投影:

Projections.SqlProjection(
       " subid - 1 as innerId" // sql statement 
       , new[] { "innerId" }   // its alias
       , new IType[] { NHibernateUtil.Int32 }) // type is int

注意:我希望最后的预测为MAX

相关问题