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.
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\")");
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.