As you are learning how to use NHibernate many of the ‘common’ things you are used to doing with standard SQL crop up. One of them for me was to have the ability to perform a Count() query. If I were using straight SQL my query may look something like this:
SELECT COUNT( FieldNameHere )
FROM SomeTableTable
WHERE Field1Here = 51
AND Field2Here = 1
AND Field3Here = 1
Like many things in Nhibernate there are many ways to solve the same problem, but one way I found was to create the criteria query as below:
var count = (Int32) Session.CreateCriteria( typeof( SomeTableHere ) )
.Add( Expression.Eq( "Field1Here", 1) )
.Add( Expression.Eq( "Field2Here", (Int32) 2) )
.Add( Expression.Eq( "Field3Here", 3) )
.SetProjection( Projections.Count( "CountFieldHere" ) ).UniqueResult();
And the result from the above syntax would produce the following (the sql below was given to me via NHProfiler – kick ass tool EVERYONE should be using).
SELECT count(this_.OUTBOUND_STAGING_QUEUE_ID) as y0_
FROM SomeTableHere this_
WHERE this_.Field1Here= 51 /* @p0 */
and this_.Field2Here = 1 /* @p1 */
and this_.Field3Here = 1 /* @p2 */
As you can see creating a count query with NHibernate is pretty straight forward and will generate the exact SQL you would expect.
Till next time,
Posted
04-16-2009 7:18 AM
by
Derik Whittaker