nreco / lambdaparser

Runtime parser for string expressions (formulas, method calls). Builds dynamic LINQ expression tree and compiles it to lambda delegate.
http://www.nrecosite.com/
MIT License
307 stars 55 forks source link

Is it possible to build lambda for entity framework queries #18

Open gopala000 opened 5 years ago

gopala000 commented 5 years ago

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();
}

VitaliyMF commented 5 years ago

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).

gopala000 commented 5 years ago

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)