你的方法有两个问题。首先,您不能在 Linq 表达式中使用 null 传播运算符。测试这段代码:
var account = new Account();
// will cause "error CS8072: An expression tree lambda may not contain a null propagating operator"
Expression<Func<string>> accountNumber = () => account?.AccountNumber;
第二个也是主要的问题是你的AccountNumber
将被编译成get_AccountNumber
方法,并且您无法使用 Linq to SQL 调用任意方法。您可以测试这段代码:
public class AssetFileRecord
{
//...
public string AccountNumber => Account != null ? Account.AccountNumber : null;
}
虽然可以编译它,但它会产生相同的运行时异常。
解决此问题的一种可能方法是创建一个包含复杂属性表达式的映射:
var map = new Dictionary<string, Expression>
{
{
"AssetFileRecord.AccountNumber", // type and property
(Expression<Func<AssetFileRecord, string>>) (
afr => afr.Account != null ? afr.Account.AccountNumber : null
)
}
};
现在您可以重写构建动态的方法OrderBy
关于这张地图:
private static IQueryable<T> DynamicOrderBy<T>(
IQueryable<T> source,
string sortProperty,
Dictionary<string, Expression> map)
{
var type = typeof(T);
var parameter = Expression.Parameter(type, "p");
var property = type.GetProperty(sortProperty, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
Expression whereLambda;
if (!map.TryGetValue($"{type.Name}.{sortProperty}", out whereLambda))
{
var propertyAccess = Expression.MakeMemberAccess(parameter, property);
whereLambda = Expression.Lambda(propertyAccess, parameter);
}
// else we just using a lambda from map
// call OrderBy
var query = Expression.Call(
typeof(Queryable),
"OrderBy",
new[] {type, property.PropertyType},
source.Expression,
whereLambda
);
return source.Provider.CreateQuery<T>(query);
}