Home > Software engineering >  Prevent deferred execution of extension method or predicate in where cause c# linq
Prevent deferred execution of extension method or predicate in where cause c# linq

Time:12-08

Basically I am creating an extension/predicate method to Mimic .contains behavior

NHibernate Query

var query = currentSession.Query<MyEntity>().Where(x => Ids.In("|"   x.Id.ToString()   "|")).Select(y=> y); 

In the above query .In is my extension method.

The above query executes in a deferred manner for extension method /predicate which cause error, but the same query when used with .Contains executes without any problems. Also my extension method or predicate break point is never hit due to deferred execution by Linq.

var query = currentSession.Query<MyEntity>().Where(x => Ids.Contains("|"   x.Id.ToString()   "|")).Select(y=> y); 

I have seen some suggestions where using .toList() would make it execute immediately , but I cant use that because I am just forming a query here which will be executed later.

CodePudding user response:

Thanks to @Svyatoslav Danyliv I was able to achieve what I want with LinqKit

    Expression<Func<T, bool>> criteria = p => Ids.Contains("|"   x.Id.ToString()   "|");
        
    var query = currentSession.Query<MyEntity>().Where(criteria.Expand()).Select(y=> y); 
  • Related