我的目标是为动态全文搜索创建一个子查询表达式树。在 SQL 中,它相当于
SELECT *
FROM MV
WHERE MV.ID IN (SELECT ID
FROM MVF
WHERE title = "foo" OR Description = "foo")
所以基本思想是创建 FTS 子查询,从中获取 ID 并将它们用于 In 谓词。我的问题是第二部分。
// Get subquery for FTS tables
ParameterExpression ftsParam = Expression.Parameter(typeof(MVF), "mvfts");
var wphrase = Expression.Constant("foo");
var methodInfo = typeof(string).GetMethod("Equals", new Type[] { typeof(string) });
var ftsID = Expression.Property(ftsParam, "ID");
var ftsTitle = Expression.Property(ftsParam, "Title");
var ftsDescrip = Expression.Property(ftsParam, "Description");
var texp = Expression.Call(ftsTitle, methodInfo, wphrase);
var dexp = Expression.Call(ftsDescrip, methodInfo, wphrase);
var ftsExp = Expression.Or(texp, dexp);
// Now get ids from the above fts resultset
// THE ASSIGNMENT BELOW THROWS
var selectExp = Expression.Call(typeof(IEnumerable<MVF>), "Select", new Type[]
{
typeof(long)
},
ftsExp,
Expression.Lambda<Func<MFV, long>>(
ftsID,
ftsParam
)
);
// Now set up MV table reference
ParameterExpression vParam = Expression.Parameter(typeof(MV), "mv");
var mvID = Expression.Property(vParam, "MVID");
var containsInfo = typeof(IEnumerable<long>).GetMethod("Contains", new Type[] { typeof(long) });
// Now combine expression to get those mvs with ids in the result set of fts query
var containsExp = Expression.Call(selectExp, containsInfo, mvID);
return Expression.Lambda<Func<MV, bool>>(containsExp, vParam);
异常(exception)是:
No generic method 'Select' on type 'System.Collections.Generic.IEnumerable`1[MVF]' is compatible with the supplied type arguments and arguments. No type arguments should be provided if the method is non-generic.
最佳答案
所讨论的表达式所需的两种方法都是 Enumerable
的静态泛型扩展方法(最重要的是 static 和 generic)类:
public static IEnumerable<TResult> Select<TSource, TResult>(
this IEnumerable<TSource> source,
Func<TSource, TResult> selector
)
public static bool Contains<TSource>(
this IEnumerable<TSource> source,
TSource value
)
“调用”此类方法最方便的方式如下 Expression.Call
方法重载:
public static MethodCallExpression Call(
Type type,
string methodName,
Type[] typeArguments,
params Expression[] arguments
)
Type type
参数是定义被调用方法的类的类型(在本例中为 typeof(Enumerable)
)和 Type[] typeArguments
是具有泛型类型参数类型的数组(对于非泛型方法为空,对于 Select
应该是 { typeof(TSource), typeof(TResult) }
> 和 { typeof(TSource) }
用于包含
)。
将其应用到您的场景中:
var selectExp = Expression.Call(
typeof(Enumerable),
"Select",
new { typeof(MFV), typeof(long) },
ftsExp,
Expression.Lambda<Func<MFV, long>>(ftsID, ftsParam)
);
和
var containsExp = Expression.Call(
typeof(Enumerable),
"Contains",
new [] { typeof(long) },
selectExp,
mvID
);
关于c# - 带有子查询的表达式树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49827908/