NHibernate QueryOver extensibility

2019-08-14 16:38发布

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?

1条回答
Ridiculous、
2楼-- · 2019-08-14 16:57

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?

查看更多
登录 后发表回答