【发布时间】:2013-05-23 15:42:28
【问题描述】:
我使用以下扩展方法在 LINQ-To-Entities 上执行包含:
public static class Extensions
{
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");
if (!collection.Any())
return query.Where(t => false);
ParameterExpression p = selector.Parameters.Single();
IEnumerable<Expression> equals = collection.Select(value =>
(Expression)Expression.Equal(selector.Body,
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));
}
//Optional - to allow static collection:
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);
}
}
当我调用扩展方法来检查 id 列表是否在特定表中时,它可以正常工作,并且我会返回 id 列表,如下所示:
List<int> Ids = _context.Persons
.WhereIn(x => x.PersonId, PersonIds)
.Select(x => x.HeaderId).ToList();
当我执行下一条语句时,它抱怨 LINQ-To-Entities 无法识别 Contains(int32),但我认为我不再反对实体,而是反对整数的集合。
predicate = predicate.And(x=> Ids.Contains(x.HeaderId));
如果我有一个逗号分隔的字符串,例如“1,2,3”,那么以下工作:
predicate = predicate.And(x=>x.Ids.Contains(x.HeaderId));
我正在尝试获取返回的列表并创建逗号分隔的字符串列表,这里的问题是,现在当我执行predicate = predicate.And(x=>sb.Contains(x.HeaderId.ToString()); 时,它抱怨它不喜欢 ToString()。
我也试过这样做:
predicate = predicate.And(x=>Extensions.WhereIn(Ids, x.id));, but it can't resolve WhereIn. It says I must add `<>`, but I am not sure what to add here and how implement it.
【问题讨论】:
-
代码格式化了一点。
-
“谓词”从何而来?它是 IQueryable 吗?
-
@SamBauwens - albahari.com/nutshell/predicatebuilder.aspx
-
为什么要显示 WhereIn 扩展方法?如果 Ids 真的是
List<int>,我们不介意你是如何得到它的。问题似乎来自 PredicateBuilder(猜你用这个) -
@Xaisoft:你已经回答了你自己的问题。 .NET3.5 中的 EF 不支持
IEnumerable<T>.Contains。就是这样。
标签: c# entity-framework linq-to-entities