反射中的表达式可为空类型

时间:2018-08-02 02:44:43

标签: c# reflection

我有一种方法可以为实体框架生成表达式(i => ids.Contains(i.SomeProperty))。一切正常!但是,当我的属性类型为Nullable时,我会出错。我如何获得(i => ids.Contains(i.SomeProperty.Value)) 或(i => ids.Contains(i.SomeProperty.GetValueOrDefault()))为可空类型

  public static IQueryable Where(this IQueryable source, string propertyName, IEnumerable searchValues)
    {
        //Get target's T 
        var targetType = source.GetType().GetGenericArguments().FirstOrDefault();
        if (targetType == null)
            throw new ArgumentException("Should be IEnumerable<T>", "target");

        //Get searchValues's T
        Type searchValuesType;
        if (searchValues.GetType().IsArray)
            searchValuesType = searchValues.GetType().GetElementType();
        else
            searchValuesType = searchValues.GetType().GetGenericArguments().FirstOrDefault();

        if (searchValuesType == null)
           throw new ArgumentException("Should be IEnumerable<T>", "searchValues");

        //Create a p parameter with the type T of the items in the -> target IEnumerable<T>
        var containsLambdaParameter = Expression.Parameter(targetType, "i");

        //Create a property accessor using the property name -> p.#propertyName#
        var property = Expression.Property(containsLambdaParameter, targetType, propertyName);

        //Create a constant with the -> IEnumerable<T> searchValues
        var searchValuesAsConstant = Expression.Constant(searchValues, searchValues.GetType());

        //Create a method call -> searchValues.Contains(p.Id)
        var containsBody = Expression.Call(typeof(Enumerable), "Contains", new[] { searchValuesType }, searchValuesAsConstant, property);

        //Create a lambda expression with the parameter p -> p => searchValues.Contains(p.Id)
        var containsLambda = Expression.Lambda(containsBody, containsLambdaParameter);

        return source.Provider.CreateQuery(
            Expression.Call(
                typeof(Queryable), "Where",
                new Type[] { source.ElementType },
                source.Expression, Expression.Quote(containsLambda)));

    }

0 个答案:

没有答案