C # Entity Framework query using boolean expressions?
I am very new to Entity and I am trying to find all elements in a DbSet that match a boolean condition that is passed as a string:
Example:
string condition = "Weight > 30 && Age == 20";
var results = context.Data.FindIf(condition);
where Weight and Age are Data properties, and the boolean condition given may vary. I can easily code it using LINQ expressions, but is there a way to do it the way I described?
source to share
You can use the DynamicLinqQuery library to use string epicrests against IQueryable sources. The library is built on top of a feature described in the MSDN article Expression Trees and Dynamic Query Builders shared by @tdbeckett
It allows you to write dynamic conditions as a string, eg.
using System.Linq.Dynamic;
var query =
db.Customers.
Where("City = @0 and Orders.Count >= @1", "London", 10);
A Nuget package is available for this:
Install-Package DynamicQuery
After the installation is complete, you can find the HTML file added to the project for help.
source to share
Expression trees can do what you want here. You can parse the string to build an expression tree.
https://msdn.microsoft.com/en-us/library/bb397951.aspx
source to share
Can you 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");
source to share