【问题标题】:Accessing expression bodied members to build expression trees访问表达式主体成员以构建表达式树
【发布时间】:2019-02-10 22:19:33
【问题描述】:

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

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

我无法访问作为 AssetFileRecord 虚拟属性的属性 AccountNumber。

以下是适用于任何其他非表达式实体属性的当前代码。

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'

预期结果:它应该在最后生成的表达式树上附加一个 order by 表达式;虽然它没有这样做,但当试图通过表达式主体属性成员进行排序时。

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

【问题讨论】:

  • 确定Expression.Quote是必要的吗?
  • @MarcoLuzzara OrderBy 的内部实现使用它。
  • 研究使用LINQKit。
  • 感谢@MarcoLuzzara,您的意见。
  • 感谢@NetMage 的输入。

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


【解决方案1】:

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

【讨论】:

  • 非常感谢!这正是我一直在寻找的。更进一步,我最初认为我可以使用相同的方法(您提到的)来访问上面编辑的代码中的折旧属性注释下的属性。但是运气不好,我得到了与响应相同的错误。你能检查一下有什么问题吗?或者是否需要更改方法以适应上述添加的字段?
  • @AbhayNagaraj 您不能将常规 C# 方法与 Expression 混合使用。如果你想重用Depreciation() 方法,它必须返回一个表达式。无论如何,这听起来像是另一个问题
  • 有道理。你能看看这个问题吗? stackoverflow.com/q/54898363/9646463
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-06
  • 1970-01-01
  • 2023-03-12
相关资源
最近更新 更多