【发布时间】:2017-03-20 16:25:58
【问题描述】:
我的数据模型中的类实现了一个接口:
public class SomeType : ISomeInterface
public interface ISomeInterface
在我的 WCF 查询拦截器中,我想使用一个通用的 Expression,以便我可以对多种类型使用相同的过滤逻辑:
[QueryInterceptor("SomeType")]
public Expression<Func<SomeType, bool>> SomeTypeInterceptor()
{
// Return CommonFilter() or extend it with logic unique to SomeType
}
private Expression<Func<ISomeInterface, bool>> CommonFilter()
{
// Use ISomeInterface methods and properties to build expression
// ...
}
问题是让Expression<Func<SomeType, bool>> 与Expression<Func<ISomeInterface, bool>> 相处。
尝试 #1
只返回普通表达式不会编译:
[QueryInterceptor("SomeType")]
public Expression<Func<SomeType, bool>> SomeTypeInterceptor()
{
return CommonFilter();
}
出现错误:
无法将类型
System.Linq.Expressions.Expression<System.Func<ISomeInterface, bool>>隐式转换为System.Linq.Expressions.Expression<System.Func<SomeType, bool>>
尝试 #2
使用查询拦截器定义中的接口:
[QueryInterceptor("SomeType")]
public Expression<Func<ISomeInterface, bool>> SomeTypeInterceptor()
编译,但是WCF不喜欢这样,向客户端返回错误:
“DataService”类型上的“SomeTypeInterceptor”方法的返回类型是
System.Linq.Expressions.Expression<System.Func<ISomeInterface, System.Boolean>>类型,但查询拦截器需要可分配给System.Linq.Expressions.Expression<System.Func<SomeType, System.Boolean>>的类型。
尝试 #3
看着问题How can I cast an expression from type interface, to an specific type和C# How to convert an Expression<Func<SomeType>> to an Expression<Func<OtherType>>,我尝试实现this answer:
[QueryInterceptor("SomeType")]
public Expression<Func<SomeType, bool>> SomeTypeInterceptor()
{
Expression<Func<SomeType, bool>> someTypeExpression =
someType => CommonFilter().Compile().Invoke(someType);
return someTypeExpression;
}
但现在 LINQ to Entities 不喜欢这样,返回错误:
LINQ to Entities 无法识别方法 'Boolean Invoke(ISomeInterface)' 方法,并且该方法无法转换为存储表达式。
有没有办法在 WCF 查询拦截器中使用通用逻辑?
【问题讨论】:
标签: c# linq wcf interface expression