Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how te create dynamic queries?

I have a repository that use EF 4.4 and a class that has the parameters that I can use to filter my query. Also, I use SQLQuery to create my dynamic raw sql to add conditions according to the properties of my parameter class that are not null.

However, SQL Query does not allow eager loading, so I would like to know how I can create dynamic queries with LinQ to be able to use eager loading.

I have readed this post

that use a parameter class, but only use one parameter to do the query, but if I have many parameters in the class and I have many combitanitions, how can do it? I need to do many else if to have in consideration all the posible combinations? When I use raw sql, I only need to check if a paratemer is null or not and if is not null, only check if is the first paratemer to add the "where" or if other I add the "and". So the code is short because I don't need to consider all the posible combinations of parameters.

How can I do dynamic queries with LinQ?

Thanks.

like image 752
Álvaro García Avatar asked Jun 18 '26 09:06

Álvaro García


1 Answers

var query = ctx.Books;

if ( param1 != null )
   query = query.Where( b => b.Param1 == param1 );

if ( another2 > 0 )
   query = query.Where( b => b.Amount > another );

etc.

As you can see, clauses are composed dynamically based on arbitrary external criteria which at the end gives you complete control over the query structure.

Note that EF still executes it as a single db query.

like image 69
Wiktor Zychla Avatar answered Jun 20 '26 22:06

Wiktor Zychla



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!