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

问题描述 投票:2回答:1

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

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'

预期结果:它应该通过表达式将顺序附加到最后生成的表达式树中;虽然它没有这样做,当试图通过表达身体的财产成员订购。

有人可以帮助我让这个工作。

c# linq entity-framework-6 expression-trees
1个回答
2
投票

你的方法有两个问题。首先,您不能在Linq表达式中使用空传播运算符。测试此代码:

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);
}
© www.soinside.com 2019 - 2024. All rights reserved.