3

I'm very new to Entity, and I'm trying to find all elements in a DbSet object that match a boolean condition that's passed as a string:

Example: 
string condition = "Weight > 30 && Age == 20";
var results = context.Data.FindIf(condition);

where Weight and Age are properties of Data, and the boolean condition given can vary. I can hard code it easily with LINQ expressions but is there a way to do it in the way I described?

1
  • 2
    Take a look to a code sample called Dynamic LINQ Commented Jul 30, 2015 at 17:15

3 Answers 3

5

Expression trees can do want you want here. You can parse the string to build the expression tree.

https://msdn.microsoft.com/en-us/library/bb397951.aspx

https://msdn.microsoft.com/en-us/library/bb882637.aspx

Sign up to request clarification or add additional context in comments.

Comments

2

You could use a raw SQL query and just execute normal SQL against it?

context.Database.SqlQuery<Data>("SELECT * FROM [DataTable] WHERE Weight > 30 AND Age = 20");

3 Comments

The boolean string condition is passed to me and I have to process that, I can't use a SQL query unless I construct one from that string.
you can use expression trees
Is that condition guaranteed to be a valid LINQ query or do you have to validate it anyway? If you have to mess with it anyway, then this answer is an easy to understand candidate IMO, but if you know it'll be valid LINQ, I recommend @tdbeckett's answer.
1

You can use the DynamicLinqQuery library to use string epxressions against the IQueryable sources. The library is built on top of feature described in MSDN article of Expression tree and dynamic query builders shared by @tdbeckett

It allows you to write dynamic conditions as string e.g.

using System.Linq.Dynamic;

var query = db.Customers. Where("City = @0 and Orders.Count >= @1", "London", 10);

There's a Nuget package available for this:

Install-Package DynamicQuery

One you finish installation you can find an HTML file added in the project for help documentation.

1 Comment

Thanks, this is exactly what I needed, worked like a charm! For future reference to anyone else, I used var results = db.Data.Where(queryRequest); where queryRequest is a string containing a boolean expression.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.