Slicing & Dicing Queries with NHibernate

This was how I started the day, interesting problem, and I like the solution:

DetachedCriteria getMaxScanDateForScan = DetachedCriteria.For<ScanResult>()
	.SetProjection(Projections.Max("ScanDate"))
	.Add(Property.ForName("ScanUri").EqProperty("scan.Id"));
DetachedCriteria hasResults = DetachedCriteria.For<ScanResult>()
   .SetProjection(Projections.Id())
   .Add(Property.ForName("ScanUri").EqProperty("scan.Id"));

criteria
	.CreateCriteria("Results", "result", JoinType.LeftOuterJoin)
	.SetProjection(
	Projections.ProjectionList()
		.Add(Projections.Property("scan.Id"), "Id")
		.Add(Projections.Property("scan.Uri"), "Uri")
		.Add(Projections.Property("scan.DaysNotice"), "DaysNotice")
		.Add(Projections.Property("scan.EnableScan"), "EnableScan")
		.Add(Projections.Property("result.ScanDate"), "LastScan")
		.Add(Projections.Property("result.Status"), "Status")
		.Add(Projections.Property("result.Message"), "Message")
	)
	.Add(Expression.Disjunction()
		.Add(Subqueries.PropertyEq("result.ScanDate", getMaxScanDateForScan))
		.Add(Subqueries.NotExists(hasResults))
	);

IList list = criteria
		.GetExecutableCriteria(session)
		.SetResultTransformer(new AliasToBeanResultTransformer(typeof (ScanURIReport)))
		.List();

Print | posted on Thursday, August 30, 2007 4:43 PM

Feedback


Gravatar

# re: Slicing & Dicing Queries with NHibernate 8/30/2007 5:42 PM Steve

Very intuitive....lol :)

What does the SetProjection call do as far as the TSQL generated?


Gravatar

# re: Slicing & Dicing Queries with NHibernate 8/30/2007 8:59 PM Ayende Rahien

Think about SetProjection as setting what will be in the SELECT clause.


Gravatar

# re: Slicing & Dicing Queries with NHibernate 8/30/2007 10:49 PM josh

intersting.. (still new to nhibernate) basically you're setting up the subqueries in seperate statements.?


Gravatar

# re: Slicing & Dicing Queries with NHibernate 8/31/2007 9:44 AM Markus Zywitza

I wish that such examples with explanation were part of the NHibernate Reference. Its section on Criteria Queries is quite short and covers only the basics :-(

-Markus


Gravatar

# re: Slicing & Dicing Queries with NHibernate 8/31/2007 4:59 PM Craig Neuwirt

Where is the scan alias set and where is criteria created


Gravatar

# re: Slicing & Dicing Queries with NHibernate 9/2/2007 2:25 PM Ayende Rahien

craig,
ICriteria criteria = DetachedCriteria.For<ScanUrl>("scan");

Comments have been closed on this topic.