lambdaparser icon indicating copy to clipboard operation
lambdaparser copied to clipboard

Is it possible to build lambda for entity framework queries

Open gopala000 opened this issue 5 years ago • 2 comments

I have a requirement to convert predicates issued as string to lambda used for EF queries. Is it possible with lambdaparser? Code snippet will be helpful. Thanks

Example: using (var context = new EntityContext()) { var customersList = context.Customers .Where(c => "c.Invoices.Count > 2") .ToList();
}

gopala000 avatar Jul 09 '19 16:07 gopala000

Technically you can try to use NReco.LambdaParser in this way: parse user-entered expression with Parse method, get Expression and then traverse it and build another Expression that is compatible with EF Where.

However I don't think that this is very good idea: LambdaParser supports syntax (properties/method calls ) that you'll not be able to convert to SQL. If you need parser for user-defined conditions that can be easily converted to SQL take a look to Relex parser (which is part of NReco.Data library, see also https://github.com/nreco/data/wiki/Relex).

VitaliyMF avatar Jul 09 '19 16:07 VitaliyMF

Thanks for the quick response. I looked at both and decided to go with below approach:

            var filter = "(record, user) => record.FileName == \"b7\" && user.FirstName == \"Gopal\""; //test
            var options = ScriptOptions.Default.AddReferences(typeof(UserRecord).Assembly);

            Func<UserRecord, ApplicationUser, bool> filterExpression = await CSharpScript.EvaluateAsync<Func<UserRecord, ApplicationUser, bool>>(filter, options);

and use it in where clause like this:

                    && filterExpression(ur, ro)

gopala000 avatar Jul 09 '19 17:07 gopala000