我想过滤一个实现接口的实体列表。

模型:

public interface IEntity
{
    int Id {get; set;}
}

public interface IOther
{
    int Other {get; set;}
}

public class MyEntity : IEntity, IOther
{
    public int Id {get; set;}
    public int Other {get; set;}
}


控制器:

public abstract class GenericApiController<T> : ApiController
    where T : IEntity
{
    public HttpResponseMessage Get(int other)
    {
        var query = Repository.AsQueryable()
                              .Cast<IOther>()
                              .Where(x => x.Other == other);

        return Ok(query.ToList());
    }
}


但是,我收到“ LINQ to Entities仅支持转换EDM基本类型或枚举类型”异常。

一种解决方案是在GenericApiController上具有where T : IOther,但是可悲的是我不能这样做,因为不是每个IEntity都也实现IOther。

我正在研究是否可以执行以下操作:

public abstract class GenericApiController<T> : ApiController
    where T : IEntity
{
    public HttpResponseMessage Get(int other)
        where T : IOther
    {
        var query = Repository.AsQueryable()
                              .Where(x => x.Other == other);

        return Ok(query.ToList());
    }
}


请注意对Get()的额外限制,但这是不可能的(据我所知)。

有什么建议么?

最佳答案

您可以为继承IOther的类编写特定的控制器,但不能完全解决问题。

在下面的表达式中(RepositoryIQueryable<T>T继承自IOther),C#编译器考虑从TIOther的隐式强制转换,以调用Other属性。

var query = Repository.Where(x => x.Other == other);


因此,您可以对实体进行强制转换和LINQ相同的NotSupportedException

解决方案是在运行时使用Reflection构建查询。

这是为了限制编译器在表达式级别上的工作,并在运行时执行从表达式到函数的转换。

通用查询表达式为:

Expression<Func<IQueryable<T>, int, IQueryable<T>>> QueryExpression =
    (repository, other) => repository.Where(x => x.Other == other);


使用调试控制台,您将看到编译器如何添加隐式转换器:

QueryExpression.ToString():(存储库,其他)=>存储库。(x =>(Convert(x).Other == other))

此表达式有两件事需要更改:


消除转换器的使用
调用Other声明的T属性而不是IOther声明的属性


为此,我们使用ExpressionVisitor

public abstract class GenericApiControllerForIOther<T> : ApiController
    where T : IOther
{
    public HttpResponseMessage Get(int other)
    {
        var query = QueryFunction(Repository, other);
        return Ok(query.ToList());
    }

    // the generic query expression
    static Expression<Func<IQueryable<T>, int, IQueryable<T>>> QueryExpression =
        (repository, other) => repository.Where(x => x.Other == other);

    // the function built from the generci expression
    static Func<IQueryable<T>, int, IQueryable<T>> queryFunction = null;
    static Func<IQueryable<T>, int, IQueryable<T>> QueryFunction
    {
        get
        {
            if (queryFunction == null)
            {
                // rebuild a new lambda expression without reference to the IOther type
                TypeReplacer replacer = new TypeReplacer(typeof(IOther), typeof(T));
                Expression newExp = replacer.Visit(QueryExpression.Body);
                Expression<Func<IQueryable<T>, int, IQueryable<T>>> newLambdaExp = Expression.Lambda<Func<IQueryable<T>, int, IQueryable<T>>>(newExp, QueryExpression.Parameters);
                // newLambdaExp.ToString(): (repository, other) => repository.Where(x => (x.Other == other))
                // convert the expression to a function
                queryFunction = newLambdaExp.Compile();
            }
            return queryFunction;
        }
    }

    class TypeReplacer : ExpressionVisitor
    {
        public TypeReplacer(Type oldType, Type newType)
        {
            OldType = oldType;
            NewType = newType;
        }

        Type OldType;
        Type NewType;

        protected override Expression VisitMember(MemberExpression node)
        {
            // replace IOther.Property by T.Property
            MemberInfo memberInfo = node.Member;
            if (memberInfo.DeclaringType == OldType)
            {
                MemberInfo newMemberInfo = NewType.GetMember(memberInfo.Name).First();
                return Expression.MakeMemberAccess(Visit(node.Expression), newMemberInfo);
            }
            return base.VisitMember(node);
        }

        protected override Expression VisitUnary(UnaryExpression node)
        {
            // remove the Convert operator
            if (node.NodeType == ExpressionType.Convert
                && node.Type == OldType
                && node.Operand.Type == NewType)
                return node.Operand;
            return base.VisitUnary(node);
        }
    }
}

10-04 16:37