CodePaste Logo
New Snippet New Snippet Recent Snippets Recent Snippets My Snippets My Snippets Web Code Search Snippets Search
Sign inor Register
Language: C#

Conditional NHibernate Projection

1266 Views
Copy Code Show/Hide Line Numbers
// pseudo: if month(entered) greater than or equal to 7, return year(entered)
// else return year(entered)-1 (for school year conversion)
// returns distinct list of "school years"
 
var criteria = Session.CreateCriteria<MyEntity>();
var convertToSchoolYearProjection = 
Projections.Conditional(
 Restrictions.Ge(
  Projections.SqlFunction("month", 
    NHibernateUtil.Int32, 
    Projections.Property("Entered")), 7),
  Projections.SqlProjection("year(EnteredDate) as schoolyear", 
    new[] { "schoolyear" }, 
    new IType[] { NHibernateUtil.Int32 }),
  Projections.SqlProjection("year(EnteredDate)-1 as schoolyear", 
    new[] { "schoolyear" }, 
    new IType[] { NHibernateUtil.Int32 })
);
            
criteria.SetProjection(Projections.Distinct(convertToSchoolYearProjection));
return InTransaction(() => criteria.List<int>() as List<int>);
by David R. Longnecker
  May 21, 2010 @ 7:58am
Tags:
Description:
Result SQL:

SELECT distinct (case when datepart(year, this_.Entered) >= @p0 then year(Entered) else year(Entered)-1 end) as y0_ FROM dbo.MyEntities this_;@p0 = 7

Add a comment


Report Abuse
brought to you by:
West Wind Techologies



If you find this site useful and use it frequently please consider making a donation to support this free service.
Donate