Dynamic LINQ with ICollection.Any()

dynamic-linq entity-framework-6 linq

Question

How can I use Dynamic LINQ on navigation properties that are collections?

For example, if I want all the orders with certain no. I could do something like:

var searchTerm = "123456";
var query = context.Orders.Where(o => o.ErpOrderNo.Contains(searchTerm));
var dlQuery = context.Orders.Where("ErpOrderNo.Contains(@0)", searchTerm);

However, if I want all the orders where some order line has some no.... what can I do?

var searchTerm = "123456";
var query = context.Orders.Where(o => o.OrderItems.Any(oi => oi.ErpOrderItemNo.Contains(searchTerm)));
var dlQuery = ??

Any help or hint will be appreciated.

1
0
5/2/2018 8:45:27 PM

Accepted Answer

It's possible as soon as you follow the Expression Language rules.

For instance, string literals must be enclosed in double quotes:

query = db.Customers.Where("Categories.Any(Code == \"Retail\")");
4
6/10/2016 6:01:06 AM

Popular Answer

You can build your own runtime Expression:

Expression<Func<Customer, bool>> myRuntimeExpression = null;

if(condition1)
{
    myRuntimeExpression = cust => cust.Categories.Any(cat => cat.Code == "Retial"); // or some local variable
}
else if(condition2)
{
    myRuntimeExpression = cust => cust.Categories.Any(cat => cat.Id = someId) == false;
}
else if(condition3)
{

}

var query = DB.Customers.Where(myRuntimeExpression);

However, if you need to build more complex queries have a look at Dynamic Queries in Linq Using Expressions.



Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow