虽然不是我想要的解决方案(让它成为一个内置功能,伙计们!),但我找到了一种方法来做我想做的事,尽管方式有点有限(到目前为止,我只支持直接Where()
过滤)。
首先,我制作了一个自定义ActionFilterAttribute
类。它的目的是在它完成它的事情之后采取行动EnableQueryAttribute
,因为它修改了EnableQueryAttribute
已经产生的查询。
在您的通话中,在通话前GlobalConfiguration.Configure(config => { ... })
添加以下内容:config.MapODataServiceRoute()
config.Filters.Add(new NavigationFilterAttribute(typeof(NavigationFilter)));
它必须在之前,因为这些OnActionExecuted()
方法是以相反的顺序调用的。您还可以使用此过滤器装饰特定的控制器,尽管我发现很难确保它以正确的顺序运行。这NavigationFilter
是您自己创建的课程,我将在更远的地方发布一个示例。
NavigationFilterAttribute
和它的内部类,anExpressionVisitor
的注释记录相对较好,所以我将在下面粘贴它们而不做进一步的注释:
public class NavigationFilterAttribute : ActionFilterAttribute
{
private readonly Type _navigationFilterType;
class NavigationPropertyFilterExpressionVisitor : ExpressionVisitor
{
private Type _navigationFilterType;
public bool ModifiedExpression { get; private set; }
public NavigationPropertyFilterExpressionVisitor(Type navigationFilterType)
{
_navigationFilterType = navigationFilterType;
}
protected override Expression VisitMember(MemberExpression node)
{
// Check properties that are of type ICollection<T>.
if (node.Member.MemberType == System.Reflection.MemberTypes.Property
&& node.Type.IsGenericType
&& node.Type.GetGenericTypeDefinition() == typeof(ICollection<>))
{
var collectionType = node.Type.GenericTypeArguments[0];
// See if there is a static, public method on the _navigationFilterType
// which has a return type of Expression<Func<T, bool>>, as that can be
// handed to a .Where(...) call on the ICollection<T>.
var filterMethod = (from m in _navigationFilterType.GetMethods()
where m.IsStatic
let rt = m.ReturnType
where rt.IsGenericType && rt.GetGenericTypeDefinition() == typeof(Expression<>)
let et = rt.GenericTypeArguments[0]
where et.IsGenericType && et.GetGenericTypeDefinition() == typeof(Func<,>)
&& et.GenericTypeArguments[0] == collectionType
&& et.GenericTypeArguments[1] == typeof(bool)
// Make sure method either has a matching PropertyDeclaringTypeAttribute or no such attribute
let pda = m.GetCustomAttributes<PropertyDeclaringTypeAttribute>()
where pda.Count() == 0 || pda.Any(p => p.DeclaringType == node.Member.DeclaringType)
// Make sure method either has a matching PropertyNameAttribute or no such attribute
let pna = m.GetCustomAttributes<PropertyNameAttribute>()
where pna.Count() == 0 || pna.Any(p => p.Name == node.Member.Name)
select m).SingleOrDefault();
if (filterMethod != null)
{
// <node>.Where(<expression>)
var expression = filterMethod.Invoke(null, new object[0]) as Expression;
var whereCall = Expression.Call(typeof(Enumerable), "Where", new Type[] { collectionType }, node, expression);
ModifiedExpression = true;
return whereCall;
}
}
return base.VisitMember(node);
}
}
public NavigationFilterAttribute(Type navigationFilterType)
{
_navigationFilterType = navigationFilterType;
}
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
HttpResponseMessage response = actionExecutedContext.Response;
if (response != null && response.IsSuccessStatusCode && response.Content != null)
{
ObjectContent responseContent = response.Content as ObjectContent;
if (responseContent == null)
{
throw new ArgumentException("HttpRequestMessage's Content must be of type ObjectContent", "actionExecutedContext");
}
// Take the query returned to us by the EnableQueryAttribute and run it through out
// NavigationPropertyFilterExpressionVisitor.
IQueryable query = responseContent.Value as IQueryable;
if (query != null)
{
var visitor = new NavigationPropertyFilterExpressionVisitor(_navigationFilterType);
var expressionWithFilter = visitor.Visit(query.Expression);
if (visitor.ModifiedExpression)
responseContent.Value = query.Provider.CreateQuery(expressionWithFilter);
}
}
}
}
接下来,有几个简单的属性类,目的是缩小过滤范围。
如果您在PropertyDeclaringTypeAttribute
上使用其中一种方法NavigationFilter
,则仅当属性在该类型上时才会调用该方法。例如,给定一个Foo
具有 type 属性的类ICollection<Bar>
,如果您有一个具有 的过滤器方法[PropertyDeclaringType(typeof(Foo))]
,那么它只会为ICollection<Bar>
上的属性调用Foo
,而不会为任何其他类调用。
PropertyNameAttribute
做类似的事情,但对于属性的名称而不是类型。如果您有一个具有多个相同属性的实体类型ICollection<T>
,您希望根据属性名称进行不同的过滤,这可能会很有用。
他们来了:
[AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class PropertyDeclaringTypeAttribute : Attribute
{
public PropertyDeclaringTypeAttribute(Type declaringType)
{
DeclaringType = declaringType;
}
public Type DeclaringType { get; private set; }
}
[AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class PropertyNameAttribute : Attribute
{
public PropertyNameAttribute(string name)
{
Name = name;
}
public string Name { get; private set; }
}
最后,这是一个NavigationFilter
类的示例:
class NavigationFilter
{
[PropertyDeclaringType(typeof(Foo))]
[PropertyName("Bars")]
public static Expression<Func<Bar,bool>> OnlyReturnBarsWithSpecificSomeValue()
{
var someValue = SomeClass.GetAValue();
return b => b.SomeValue == someValue;
}
}