Usually I'd put my criterias/hql queries in a repository/dal class related to the entity, but lately I'be been thinking of adding another abstraction that represents what a query is, this would give me the possibility of adding common behavior to all queries (e.g. pagination) in a base class, etc.
so these are my components now;
generic interface not related to nhibernate:
public interface IQuery<T>
{
IList<T> List();
T Single();
}
Example implementation of a Criteria based query, something similar could be done with an Hql query, or a nhibernate-linq query
public abstract class CriteriaQuery<T>: IQuery<T>
{
[Inject]
public ISessionFactory SessionFactory { protected get; set; }
protected ISession Session
{
get { return SessionFactory.GetCurrentSession(); }
}
protected abstract ICriteria Configure(ICriteria criteria);
[Transaction]
public virtual IList<T> List()
{
var criteria = Session.CreateCriteria(typeof (T));
return Configure(criteria)
.List<T>();
}
[Transaction]
public virtual T Single()
{
return Configure(Session.CreateCriteria(typeof(T)))
.UniqueResult<T>();
}
}
and here a domain specific query would look like:
public interface IGetVideosQuery: IQuery<Video>
{
IGetVideosQuery Page(int index);
IGetVideosQuery PageSize(int pageSize);
IGetVideosQuery AllTime { get; }
IGetVideosQuery Today { get; }
IGetVideosQuery LastWeek { get; }
}
any thoughts on this? possible problems you see I might come across? Thanks!