LINQ表达式无法转换为基本属性

kos*_*kov 3 c# entity-framework-core .net-core

我有自定义的OrderBy实现,它仅适用于没有继承的类型,如果我想按基本类型的字段进行排序,则无法翻译LINQ表达式

public static IOrderedQueryable<TEntity> OrderBy<TEntity>(this IQueryable<TEntity> source, string orderByProperty, bool desc)
{
    if (source == null)
    {
        throw new ArgumentNullException(nameof(source));
    }

    if (string.IsNullOrEmpty(orderByProperty))
    {
        throw new ArgumentNullException(nameof(orderByProperty));
    }

    var command = desc ? "OrderByDescending" : "OrderBy";

    var type = typeof(TEntity);

    var param = Expression.Parameter(type, "p");
    var property = type.GetProperty(orderByProperty);
    var propertyAccess = Expression.MakeMemberAccess(param, property);
    var orderByExpression = Expression.Lambda(propertyAccess, param);
    var resultExpression = Expression.Call(
            typeof(Queryable),
            command,
            new Type[] { type, property.PropertyType },
            source.Expression,
            Expression.Quote(orderByExpression));
    return (IOrderedQueryable<TEntity>)source.Provider.CreateQuery(resultExpression);
}
Run Code Online (Sandbox Code Playgroud)

我正在使用entityframework core 2.2,但是非常有趣的事情是,如果我只是编写它,source.OrderBy(x=>x.someBaseField)那么它就可以毫无问题地工作,因此我的自定义实现必须有所帮助

在错误日志中,我还得到了翻译后的查询,它看起来像这样,有趣的是结尾部分

orderby new SomeType() {NewField = [entity].DbField, Id = [entity].Id}.Id desc

orderByExpression.Body {p => p.Id}

resultExpression

.Call System.Linq.Queryable.OrderByDescending(
    .Call System.Linq.Queryable.Select(
        .Call System.Linq.Queryable.Where(
            .Call System.Linq.Queryable.Where(
                .Constant<Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1[MyTypeView]>(Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1[MyTypeView]),
                '(.Lambda #Lambda1<System.Func`2[MyTypeView,System.Boolean]>)),
            '(.Lambda #Lambda2<System.Func`2[MyTypeView,System.Boolean]>)),
        '(.Lambda #Lambda3<System.Func`2[MyTypeView, MyTypeResult]>))
    ,
    '(.Lambda #Lambda4<System.Func`2[MyTypeResult,System.Guid]>))
Run Code Online (Sandbox Code Playgroud)

Iva*_*oev 5

我以前看过类似的东西。编译器生成和手动表达式之间的唯一区别是-的ReflectedType属性,PropertyInfo在编译器生成的代码中,与相同DeclaringType,在这种情况下,它是基类,而在PropertyInfovia中,type.GetProperty则是用于获取它的派生类型。

由于某些未知原因(可能是错误),这使EF Core感到困惑。解决方法是如下更改代码:

var property = type.GetProperty(orderByProperty);
if (property.DeclaringType != property.ReflectedType)
    property = property.DeclaringType.GetProperty(property.Name);
Run Code Online (Sandbox Code Playgroud)

或使用这样的帮助方法

static PropertyInfo GetProperty(Type type, string name)
{
    for (; type != null; type = type.BaseType)
    {
        var property = type.GetProperty(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);
        if (property != null) return property;
    }
    return null;
}
Run Code Online (Sandbox Code Playgroud)

为了支持嵌套属性,我将添加以下帮助器

static Expression Property(Expression target, string name) =>
    name.Split('.').Aggregate(target, SimpleProperty);

static Expression SimpleProperty(Expression target, string name) =>
    Expression.MakeMemberAccess(target, GetProperty(target.Type, name));
Run Code Online (Sandbox Code Playgroud)

然后使用

var propertyAccess = Property(param, orderByProperty);
Run Code Online (Sandbox Code Playgroud)

new Type[] { type, orderByExpression.ReturnType },
Run Code Online (Sandbox Code Playgroud)

里面的方法。