Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic Linq Where IN

How could I define a where in criteria with Dynamic Linq?

I tired workaround below but it must not work, because it doesn't make sense!

context.Records.Where("@0.Contains(ID)", new object[]{
   new string[] {"1", "2", "3"}
}); // throws error No property or field 'ID' exists in type 'String'

Edit 1:

Thanks to everybody, All you need is to use it or outerIt keyword in your Dynamic.Linq query, so in my example i just need to use outerIt:

context.Records.Where("@0.Contains(outerIt.ID)", new object[]{
   new string[] {"1", "2", "3"}
});

You can find more example and information here: Advanced Linq - Dynamic Linq query library: Add support for 'Contains' extension

like image 832
Ali Bahrami Avatar asked Dec 24 '22 08:12

Ali Bahrami


2 Answers

Other folks here introduced interesting workarounds but they are not useful if we use Dynamic.Linq library. Oleksandr Nahirniak found this question on Stackoverflow. There is also a blog post about advanced Linq queries with Dynamic.Linq which reviewdhere.

Since version 1.0.4 the library also supports Contains extension as well. It could be done just like below:

 query = Contact.GetContactsList()
                .AsQueryable()
                .Where("@0.Contains(outerIt.Country)", new List<String>() { "Austria", "Poland" }); 

or

query = Contact.GetContactsList()
               .AsQueryable()
               .Where("@0.Contains(outerIt.Country) && it.BirthDate.Year > @1", new List<string>() { "Austria", "Poland" }, 1955);

there are two keywords it and outerIt. It represent to the list that you have passed as a parameter and outerIt represent the collection itself.

So here is my working example:

context.Records.Where("@0.Contains(outerIt.ID)", new object[]{
   new string[] {"1", "2", "3"}
});
like image 152
Ali Bahrami Avatar answered Feb 09 '23 04:02

Ali Bahrami


If you work with EF you can use direct sql commands, like:

context.Database.ExecuteSqlCommand($"SELECT * FROM Records AS r WHERE r.{dynamicPropertyName} IN @ids", new string[] {"1", "2", "3"});

EDIT

Solved:

System.Linq.Dynamic - Can I use IN clause in WHERE statement

like image 42
Oleksandr Nahirniak Avatar answered Feb 09 '23 02:02

Oleksandr Nahirniak