I needed a classic “where guid in” type of query to do (though i’m not sure if i should be thinking in that way when using linq:) so i poked around a bit, but couldn’t find anything good. So here it is:
public static IQueryable<T> WhereIn<T,TMember>(this IQueryable<T> query, Expression<Func<T, TMember>> member, IList<TMember> inList) where T : BaseEntity { if (inList.Count() == 0) return query.Where(x => false); Expression<Func<TMember, bool>> expr = x => Enumerable.Contains(inList,x); var method = ((MethodCallExpression)expr.Body).Method; var expression = Expression.Call(null, method, ((MethodCallExpression)expr.Body).Arguments[0], member.Body); var lambda = Expression.Lambda<Func<T, bool>>(expression, "inLambda", member.Parameters); return inList.Count() > 0 ? query.Where(lambda) : query.Where(x => false); }
A classic example of usage would be something like this
Repository.Query<Partner>().WhereIn(x => x.Guid, partnerGuidList))
We are basically selecting partners by partnerguid, it’s very useful for paging and such.
An ispiration for this type of solution came from the this blog post for catching future values. Hope this helps!
Marc Mar 12 , 2013 at 9:35 am /
Simply:
().Where(x => partnerGuidList.Contains(x.Guid)))
Repository.Query
though both have the 2100 parameter limit issue with SQL server.
kagjes Mar 12 , 2013 at 9:55 am /
Hmm, i think for some reason that didn’t work out for me when using NHibernate, but i could be wrong, it’s been awhile:)