访问表达式主体成员以构建表达式树

时间:2019-02-10 22:19:34

标签: c# linq entity-framework-6 expression-trees

尝试使用表达式树通过表达式构建订单。但是我无法访问查询结果的类的表达式主体属性。 这是类结构:

public class AssetFileRecord : IAuditable, IEntity, INavigateToCustomValues
{
    public AssetFileRecord()
    {
        this.UpdatedTimeStamp = DateTime.UtcNow;
    }

    public AssetFileRecord GetRecord()
    {
        return this;
    }

    public Guid Id { get; set; }
    public int DisplayId { get; set; }
    public string AssetTagNumber { get; set; }
    [JObjectIgnore]
    public virtual Account Account { get; set; }
    public string AccountNumber => Account?.AccountNumber;
    public string AuditTrail { get; set; }
    public string OldTagNumber { get; set; }
    public ActivityCode ActivityCode { get; set; }

    [JObjectIgnore]
    public virtual ICollection<AssetFileRecordDepreciation> AssetFileRecordDepreciations { get; set; }
    // Depreciation Records
    public double? AccumulatedDepreciation => Depreciation()?.AccumulatedDepreciation;
    public DateTime? DepreciationAsOfDate => Depreciation()?.DepreciationAsOfDate;
    public double? LifeMonths => Depreciation()?.LifeMonths;
    public double? DepreciationBasis => Depreciation()?.DepreciationBasis;
    public double? PeriodDepreciation => Depreciation()?.PeriodDepreciation;

    private AssetFileRecordDepreciation Depreciation()
    {
        return AssetFileRecordDepreciations?.AsQueryable()?.OrderBy(d => d.AssetFileDepreciationBook.BookNo)?.FirstOrDefault();
    }
}

我无法访问属性AccountNumber,它是AssetFileRecord的虚拟属性的属性。

以下是当前代码,该代码对于任何其他非表达主体属性都适用。

var type = typeof(T);
var property = type.GetProperty(sortProperty, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
var parameter = Expression.Parameter(type, "p");
var propertyAccess = Expression.MakeMemberAccess(parameter, property);
var orderByExp = Expression.Lambda(propertyAccess, parameter);
var typeArguments = new[] { type, property.PropertyType };
var methodBase = isFirstOrderTerm ? "OrderBy" : "ThenBy";
var methodName = sortOrder == ListSortDirection.Ascending ? methodBase : $"{methodBase}Descending";
var resultExp = Expression.Call(typeof(Queryable), methodName, typeArguments, source.Expression, Expression.Quote(orderByExp));

return source.Provider.CreateQuery<T>(resultExp);

Expression.Call不会评估为有效的SQL查询,而是会引发异常。

((System.Data.Entity.Infrastructure.DbQuery<AssetFileRecord>)records).Sql = '((System.Data.Entity.Infrastructure.DbQuery<AssetFileRecord>)records).Sql' threw an exception of type 'System.NotSupportedException'

预期结果:应将按表达式的顺序附加到最后生成的表达式树中;尝试通过表达式属性属性成员进行排序时,这样做会失败。

有人可以帮我解决这个问题。

1 个答案:

答案 0 :(得分:2)

您的方法有两个问题。首先是您不能在Linq Expressions中使用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);
}