Projections.Conditional - How to use it?
Asked Answered
K

1

7

Anyone knows how to use Projections.Conditional to produce something like "case ... when..."

The following code gives a wrong query:

IProjection isError = Projections.Conditional( Expression.Eq( "event.LogLevel", eLogLevel.Fatal.ToString( ) ), Projections.Constant( 1 ), Projections.Constant( 0 ) );

ICriteria criteria = Session.CreateCriteria( typeof( LogEvent ), "event" )
  .Add( Restrictions.Eq( "event.ApplID", "LogEventViewer" ) )
  .SetProjection( Projections.ProjectionList( )
    .Add( Projections.GroupProperty( "event.ApplID" ) )
    .Add( Projections.RowCount( ), "TotalCount" )
    .Add( Projections.Sum( isError ), "ErrorCount" )
  );

The produced statement is incomplete and the order of the parameters is wrong.

exec sp_executesql N'
  SELECT this_.strApplID as y0_
    , count(distinct this_.lngLogEventID) as y1_ 
    , sum((case when this_.strLogLevel = ? then ? else ? end)) as y2_
    , this_.strApplID as y3_ 
  FROM qryLogEvent this_ 
  WHERE this_.strApplID = @p0 
  GROUP BY this_.strApplID' 
,N'@p0 nvarchar(5),@p1 int,@p2 int,@p3 nvarchar(14)'
,@p0=N'Fatal',@p1=1,@p2=0,@p3=N'LogEventViewer' 

what is the correct way to use Projections.Conditional?

Kamilah answered 3/8, 2009 at 14:43 Comment(1)
I do think it's a bug. I've tried in all sorts of ways too, and the order of the parameters is tangled up. What version of NH are you using?Workmanlike
W
2

UPDATE: The issue (NH1911) is now marked as fixed in version 2.1.1.GA. Try checking that one out!


It seems to be the use of named and positional parameters together. It does seem to be a bug, as you must have concluded too:

https://nhibernate.jira.com/browse/NH-1911

Projections.Constant uses positional and the Restriction.Eq uses named parameters. That messes up the order as desribed here, though this issue should have been fixed:

https://forum.hibernate.org/viewtopic.php?f=25&t=985944&start=0

Workmanlike answered 5/8, 2009 at 7:40 Comment(3)
NH-1098 seems not to resolve my problem. We use Version 2.1.0 GA.Kamilah
Ok. But what I tried to say, was that it has been an issue a while, and was not fixed in earlier versions - and you're using Projections.Conditional correct. And it seems that you have already reported it as a bug to the NH Jira?Workmanlike
The issue (NH1911) is now marked as fixed in version 2.1.1.GA. Try checking that one out.Workmanlike

© 2022 - 2024 — McMap. All rights reserved.