问题背景:
public IQueryable<T_Bas_PlanInfo> GetT_Bas_PlanInfoByCondition(List<string> conditions)
{
var results = this.ObjectContext.T_Bas_PlanInfo
.Where(e => conditions.Any(e2 => e.plangeneral.Contains(e2)));
return results;
}
在T_Bas_PlanInfo中的plangeneral列中查找包含conditions中任意元素的项,结果返回空(实际应该非空)。
解决方案:
对于conditions这种动态数组,需要表达式树动态生成查询语句。
扩展wherein
public static IQueryable<TEntity> WhereIn<TEntity, TValue>
(
this ObjectQuery<TEntity> query,
Expression<Func<TEntity, TValue>> selector,
IEnumerable<TValue> collection
)
{
if (selector == null) throw new ArgumentNullException("selector");
if (collection == null) throw new ArgumentNullException("collection");
ParameterExpression p = selector.Parameters.Single();
if (!collection.Any()) return query;
IEnumerable<Expression> equals = collection.Select(value =>
(Expression)Expression.Call(selector.Body,
typeof(string).GetMethod("Contains"),
Expression.Constant(value, typeof(TValue))));
Expression body = equals.Aggregate((accumulate, equal) =>
Expression.Or(accumulate, equal));
return query.Where(Expression.Lambda<Func<TEntity, bool>>(body, p));
}
public static IQueryable<TEntity> WhereIn<TEntity, TValue>
(
this ObjectQuery<TEntity> query,
Expression<Func<TEntity, TValue>> selector,
params TValue[] collection
)
{
return WhereIn(query, selector, (IEnumerable<TValue>)collection);
}
调用方式如下:
public IQueryable<T_Bas_PlanInfo> GetT_Bas_PlanInfoByCondition(List<string> conditions)
{
var results = this.ObjectContext.T_Bas_PlanInfo
.WhereIn(e => e.plangeneral, conditions);
return results;
}