我在我的服务上传递了一些参数(propertyName和arrayIds),并通过反射构建了表达式树。当我使用实体框架时,一切正常。几天前,我迁移到EF Core,但出现错误(数据为Null。无法在Null值上调用此方法或属性。)
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()*/);
var res = Expression.Convert(property, searchValuesType);
//Create a method call -> searchValues.Contains(p.Id)
var containsBody = Expression.Call(typeof(Enumerable), "Contains", new[] { searchValuesType }, searchValuesAsConstant, res);
//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, containsLambda));
}