I am trying to create an NHibernate criteria that will get me all posts that were created during a certain time of day.
For example, I want all posts that were created between the times of 12:15:00 and 2:20:00.
Post would look like this
public class Post
{
public virtual DateTime CreatedOn { get; set;}
}
And the mapping:
<class name="Post" table="Posts">
<property name="CreatedOn" not-null="true"/>
</class>
And I would like to use DetachedCriteria (this will be part of larger search)
something similar to:
var criteria = DetachedCriteria.For<Post>
.Add(Restriction.Ge("CreatedOn", Time(12, 15, 00))
.Add(Restriction.Le("CreatedOn", Time(2, 20, 00));
I know that isn’t at all correct but shows what I am trying to accomplish.
Using SQL Server as the database.
If you were to create the query directly in SQL you would use the datepart function. This question inquires about calling the datepart function from NHibernate. Basically you use the NHibernate projection: Projections.SqlFunction.
What complicates things a little is that you would need to have multiple projections, one for the hour, minute, and second (depending on the granularity you need). Also, I haven’t found a way to call datepart directly since I couldn’t find a way to pass a datepart parameter (its a non-quoted string constant). Instead, you can extend the dialect like so:
EDIT:
I would caution however to take note of query performance. Since there is no index on the time of day, even if there is an index on the date column, query performance could suffer if there are many records and this is the only column being restricted on. In this case it might be better to add explicit columns for the hour/minute.