Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
gopala000 opened this issue Jul 9, 2019 · 2 comments
Open

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

gopala000 opened this issue Jul 9, 2019 · 2 comments
Labels

Comments

@gopala000
Copy link

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
Copy link
Contributor

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
Copy link
Author

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)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants