NHibernate QueryOver extensibility

☆樱花仙子☆ 提交于 2019-12-13 19:21:04

问题


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:


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?



来源:https://stackoverflow.com/questions/13840413/nhibernate-queryover-extensibility

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!