Sly
Sly

Reputation: 15227

NHibernate QueryOver extensibility

Is it possible to extend QueryOver API by somehow? What I want to add is the fol

var criteria = QueryOver.Of<InternalAssessor>()
    .WhereRestrictionOn(x => x.Sector).HasAtLeastOneFlagSet((int)sector)

Where sector is bit flag enum. We had such criterion for ICriteria API and I can do

.Where(BitwiseRestrictions.AtLeastOneFlagSet("Sector", (int)sector))

But want to have strongly typed way of doing it. Are there any examples of extending QueryOver?

Upvotes: 1

Views: 964

Answers (1)

Radim K&#246;hler
Radim K&#246;hler

Reputation: 123901

There is, pretty straightforward way, how to take IQueryOver, search its Underlying criteria and append one, see https://gist.github.com/2304623

public static IQueryOver<TRoot, TSubType> WhereBitwiseRestriction<TRoot, TSubType>(
  this IQueryOver<TRoot, TSubType> query
  , Expression<Func<TSubType, object>> expression
  , int number)
{
  var name = ExpressionProcessor.FindMemberExpression(expression.Body);
  query.UnderlyingCriteria.Add
  (
    BitwiseRestrictions.AtLeastOneFlagSet(name, number)
  );
  return query; 
}

And use it

var criteria = QueryOver.Of<InternalAssessor>()
    ...
    .WhereRestrictionOn(x => x.Name).IsLike(searchedName) // standard
    ...
    .WhereBitwiseRestriction(x => x.Sector, (int)sector) // custom
    ...

To fulfil your request completely, we would need to introduce some man-in-the-middle object, which will hold reference to query and our BitwiseRestrictions. Another extension will immediately take it, append number and return query. Similar is doing the QueryOverRestrictionBuilder in NHibernate... but is not the above working and simple enough?

Upvotes: 2

Related Questions