Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# DynamicLinq where clause with Any()

I want to run dynamic linq with a string where clause like this:

query = db.Customers.Where("Categories.Any(Code == 'Retail')");

Customer entity has collection of categories

class Customer
{
    public List<Category> Categories {get;set;}
    ...
}

class Category
{
    public Guid Id {get;set;}
    public string Code {get;set;}
}

Can anyone please tell me is it possible to do something like this?

PS: I need where clause be string. The where clause will be generated at runtime, for this reason I can't use Linq query expression.

I'm using Telerik DataAccess.

like image 949
Daler Avatar asked Jun 10 '16 05:06

Daler


Video Answer


2 Answers

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\")");
like image 200
Ivan Stoev Avatar answered Oct 11 '22 19:10

Ivan Stoev


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.

like image 26
Zein Makki Avatar answered Oct 11 '22 21:10

Zein Makki