问题
So what I am basically trying to do is to build a dynamic sql query. User selects at least two employees through UI and wants to retrieve their schedule. I can't find a solution on how to automatize the query building process without diving into string parsing.
Take a look at this code:
List<OneEmployee> list = Employees.Where(each => each.Id == 1 || each.Id == 2).ToList();
...
IQueryable<OneDayInSchedule> query = context.Schedule.Where(each => each.property >= 10);
foreach (var v in list)
{
query = query.Where(each => each.Id == v.Id);
}
The code shown above is no good since every ".Where" clause is a logical summ. Take a look at the SQL query that represents the code.
SELECT * FROM Schedule WHERE property >= '10' AND Id = '1' AND Id = '0';
What i'm interested in is a logical alternative:
SELECT * FROM Schedule WHERE property >= '10' AND (Id = '1' OR Id = '0');
I've been sitting on this for the past few days and I can't find a solution. Is there any that does not require string parsing?
回答1:
You can use a predicate builder using LinqKit (available from NuGet).
Have a look here
You can then do something like:
List<OneEmployee> list = Employees.Where(each => each.Id == 1 || each.Id == 2).ToList();
...
IQueryable<OneDayInSchedule> query = context.Schedule.Where(each => each.property >= 10);
var predicate = PredicateBuilder.New<OneDayInSchedule>();
foreach (var v in list)
{
predicate = predicate.Or(each => each.Id == v.Id);
}
query.Where(predicate);
....
query.ToList();
....
来源:https://stackoverflow.com/questions/61559911/how-to-use-logical-alternative-in-dynamic-query-building-method