Accessing Method based Embodied Members to build e

2019-06-10 10:12发布

问题:

Trying to build an order by expression using expression trees. But I am unable to access an expression bodied property of the query result's class. This is the class structure:

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();
    }
}

I am unable to get to the property AccumulatedDepreciation which is a property of a virtual property of AssetFileRecord.

Below is the current code that works fine for any other non-expression bodied properties.

    public static IQueryable<T> BuildOrderByExpression<T>(IQueryable<T> source, string sortProperty, ListSortDirection sortOrder, bool isFirstOrderTerm = true)
    {
        var type = typeof(T);
        var property = type.GetProperty(sortProperty, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
        var parameter = Expression.Parameter(type, "p");
        // ReSharper disable once AssignNullToNotNullAttribute
        Expression orderByExp;
        var map = AssetFileRecordExpressionHelper.GetExpressionEmbodiedMemberMappings();
        if (!map.TryGetValue($"{type.Name}.{property.Name}", out orderByExp))
        {
            var propertyAccess = Expression.MakeMemberAccess(parameter, property);
            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);
    }

In the above code "map" is a dictionary of that returns appropriate expression terms for the embodied members except for the ones accessed on top of Depreciation() and is as follows.

public static Dictionary<string, Expression> GetExpressionEmbodiedMemberMappings()
        {
            var map = new Dictionary<string, Expression>
                {
                    {
                        $"{nameof(AssetFileRecord)}.{nameof(AssetFileRecord.AccountNumber)}",
                        (Expression<Func<AssetFileRecord, string>>) (
                            afr => afr.Account != null ? afr.Account.AccountNumber : null
                        )
                    }
                };
            return map;
        }

Expression.Call does not evaluate to a valid SQL query and rather throws an exception.

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

Intended result: It should append an order by expression to the expression tree generated in the end; while it's failing to do so, when tried to order by an expression bodied property member.

Can someone please help me get this working.