使用反射来创建查询,而不是在查询中。考虑:
public static IQueryable<Profile> Filter(
this IQueryable<Profile> source, string name, Guid uuid)
{
// .<name>UUID
var property = typeof(Profile).GetProperty(name + "UUID");
// p
var parExp = Expression.Parameter(typeof(Profile));
// p.<name>UUID
var methodExp = Expression.Property(parExp, property);
// uuid
var constExp = Expression.Constant(uuid, typeof(Guid));
// p.<name>UUID == uuid
var binExp = Expression.Equal(methodExp, constExp);
// p => p.<name>UUID == uuid
var lambda = Expression.Lambda<Func<Profile, bool>>(binExp, parExp);
// source.Where(p => p.<name>UUID == uuid)
return source.Where(lambda);
}
这首先构建表达式(因此,如果 name 是“测试”,它将创建与 p => p.TestUUID == uuid 对应的表达式,然后在对 Where 的调用中使用它。
因为这一步是首先完成的,而不是在表达式本身中完成,所以查询引擎不需要尝试将typeof 或GetProperty() 转换为 SQL(当然,它不能这样做)。
所以:
var filtered = MobileService.GetTable<Profile>().Filter(handler.Name, obj.uuid);
返回一个IQueryable<Profile>,并附上相应的Where。所以:
var profilesFromUUID = await MobileService.GetTable<Profile>().Filter(handler.Name, obj.uuid).ToListAsync();
作为一个整体,首先使用反射来构建查询,然后应用查询,然后异步生成一个列表,然后等待其结果。
值得注意的是,由于Filter() 将接受任何IQueryable<Profile>,因此它们可以被链接或联合。所以:
MobileService.GetTable<Profile>().Filter("A", uuid0).Filter("B", uuid1);
相当于:
from p in MobileService.GetTable<Profile>() where p.AUUID = uuid0 && p.BUUID == uuid1
还有:
MobileService.GetTable<Profile>().Filter("A", uuid0).Union(
MobileService.GetTable<Profile>().Filter("B", uuid1))
相当于:
from p in MobileService.GetTable<Profile>() where p.AUUID = uuid0 || p.BUUID == uuid1
更通用的版本是:
public static IQueryable<TSource> FilterByNamedProperty<TSource, TValue>(this IQueryable<TSource> source, string propertyName, TValue value)
{
var property = typeof(TSource).GetProperty(propertyName);
var parExp = Expression.Parameter(typeof(TSource));
var methodExp = Expression.Property(parExp, property);
var constExp = Expression.Constant(value, typeof(TValue));
var binExp = Expression.Equal(methodExp, constExp);
var lambda = Expression.Lambda<Func<TSource, bool>>(binExp, parExp);
return source.Where(lambda);
}
然后,虽然您必须在调用代码中执行 + "UUID",但您可以使用它对任何元素类型的任何 IQueryable<> 进行类似查询。