Linq Predicates

Posts   
 
    
MacSimon
User
Posts: 3
Joined: 06-Mar-2009
# Posted on: 06-Mar-2009 12:26:32   

Hi,

I would like to know if it is possible to create something like a predicatebucket for linq.

ie:

say I would have a method called getAllEntities() and I would like to create an overload of this method with a 'where-clausule' like so getAllEntities(predicate WhereClausule)

how would I handle this in linq, meaning, how can I create an pass the where clausule of the linq to the overloaded method?

an example of the where-clausule would be 'where id < 10'

Thanks.

Seth avatar
Seth
User
Posts: 204
Joined: 25-Mar-2006
# Posted on: 06-Mar-2009 15:48:36   

Here is something super generic that you could use:

          public virtual EntityCollection<T> GetItemsByExpression(Expression<Func<T, bool>> expression)
          {
                if (this.EntityTypeNumber < 0) return new EntityCollection<T>();

                using (IDataAccessAdapter adapter = _adapter.Create())
                {
                     LinqMetaData metaData = new LinqMetaData(adapter);
                     var q = (metaData.GetQueryableForEntity(this.EntityTypeNumber) as DataSource2<T>)
                                 .Where<T>(expression);
                     return (q as ILLBLGenProQuery)
                             .Execute<EntityCollection<T>>();
                }
          }

The only thing you need to somehow maintain is the EntityTypeNumber for Entity T. Also, the line

_adapter.Create()

simply returns a new DataAccessAdapter.

The way to use it is:

o.GetItemsByExpression(entity => entity.Id == 2)

Enjoy!