How to use logical alternative in dynamic query building method

旧时模样 提交于 2020-05-17 05:45:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!