问题
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