dynamicexpresso / DynamicExpresso

C# expressions interpreter
http://dynamic-expresso.azurewebsites.net/
MIT License
2.01k stars 379 forks source link

Using multiple ANY throws an exception #234

Closed saadsaeed01 closed 2 years ago

saadsaeed01 commented 2 years ago

Hello

image

I have use multiple any in the where query, but when I parse the expression, I get the following exception:

Unknown identifier 'i' (at index 31).

Can you please tell me what I am doing wrong here?

Thanks S

metoule commented 2 years ago

Hi @saadsaeed01, could you create a reproducible example? There are too many unknown classes here. Also please don't paste code as image, we can't copy it into an editor.

saadsaeed01 commented 2 years ago

Hello @metoule

Thank you for the reply.

Apologies for sending the image. I will create an example and post it here. It may take some time.

What I am trying is to access domain model Organization. Organization contains a list of funds, and those funds contain other lists such as subsectors.

Wanted to ask that whether we can create an expression with such complex relations?

Best Wishes S

metoule commented 2 years ago

Ok, I managed to reproduce the issue.

public class Organization
{
    public List<InvestorFund> InvestorFunds { get; set; } = new();
}

public class InvestorFund
{
    public List<InvestorFundSubSector> InvestorFundSubSectors { get; set; } = new();

}

public class InvestorFundSubSector
{
    public SubSector SubSector { get; set; } = new();
}

public class SubSector
{
    public string Name { get; set; }
}

void Main()
{
    var whereExpression = "organization.InvestorFunds.Any(i => i.InvestorFundSubSectors.Any(s => s.SubSector.Name == 'Test'))";
    var interpreter = new Interpreter();
    var expr1 = interpreter.ParseAsExpression<Func<Organization, bool>>(whereExpression, "organization");
}

There are two issues here:

  1. You must enable lambda expression support
  2. You must use double quotes for strings

To fix your issues, please use the following code:

var whereExpression = "organization.InvestorFunds.Any(i => i.InvestorFundSubSectors.Any(s => s.SubSector.Name == \"Test\"))"; // surround Test with double quotes
var interpreter = new Interpreter(InterpreterOptions.Default | InterpreterOptions.LambdaExpressions); // enable lambda expressions
var expr1 = interpreter.ParseAsExpression<Func<Organization, bool>>(whereExpression, "organization");

DynamicExpresso works as expected, so I'll close the issue :)