Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a dynamic query using IQueryable

I'm trying to iterate for over an string array and dynamically create a IQueryable query. Its pretty straightforward but here's where I'm stuck

var query = context.QuestionsMetaDatas.AsQueryable();

var keywords=new List<string>(){ "Test1","Test2" };

foreach(var key in keywords)
{
   query=query.Where(a=>a.Text.Contains(key));
}

Now the problem is that when the query gets generated its compiles to

select * from QuestionsMetaDatas where Text Like "Test1" AND Text Like "Test2"

Instead of AND I wanted the query to generate OR...Now how can I achieve this?

like image 826
Brian_Noronha Avatar asked Sep 12 '13 12:09

Brian_Noronha


People also ask

What is Dynamic query in C#?

Instead of using language operators or type-safe lambda extension methods to construct your LINQ queries, the dynamic query library provides you with string-based extension methods that you can pass any string expression into.

What inherits from IQueryable?

The IQueryable interface inherits the IEnumerable interface so that if it represents a query, the results of that query can be enumerated. Enumeration causes the expression tree associated with an IQueryable object to be executed.

What is IQueryable interface?

The Iterable interface was introduced in JDK 1.5. It belongs to java. lang package. In general, an object Implementing Iterable allows it to be iterated. An iterable interface allows an object to be the target of enhanced for loop(for-each loop).

What is IQueryable return?

This means that you only get back the data you query for rather than having all the data returned and then filtered down in memory on the server. Take a look at this quick example of a repository that returns IQueryable .


1 Answers

I have used predicate builder like Raphael suggested, it's just one file to include in your project, then your example becomes:

var keywords=new List<string>(){ "Test1","Test2" };

var predicate = PredicateBuilder.False<QuestionsMetaDatas>();

foreach (var key in keywords)
{
  predicate = predicate.Or (a => a.Text.Contains (key));
}

var query = context.QuestionsMetaDatas.AsQueryable().Where(predicate);

Generating the OR query your are looking for.

like image 145
Tommy Grovnes Avatar answered Sep 20 '22 01:09

Tommy Grovnes