How to create SQL Nested ANDs inside of multiple ORs using LINQ

萝らか妹 提交于 2019-12-12 12:20:52

问题


I'm trying to create the equivelant LINQ query from the below SQL example:

SELECT *
FROM FOO
WHERE 
    ((a == <val1>) AND (b == <val2>) AND (c == <val3>))
OR
    ((a == <val4>) AND (b == <val5>) AND (c == <val6>))

There will always be an a, b, and c that will be AND'd together surrounded by an OR. This pattern can occur n amount of times.

The only solution I have found that work is using LINQ Union but the SQL generated isn't what I would like.


回答1:


Try implementing the PredicateBuilder class.

Then perhaps you can use something like this:

var pred = PredicateBuilder.False<Foo>();

foreach(var criteria in myCriteriaSet)
{            
    pred = pred.Or(x => x.ID== criteria.ID && 
                        x.Name== criteria.Name &&
                        x.Created == criteria.SomeDate);
}

var matching = db.Foos.Where(pred);

This then assumes your criteria is enumerable. Modify as you need to accommodate your needs.




回答2:


You can make a long conditional statement:

var foo = from f in db.Foos.Where((f => f.A == val1 && f.b == val2 && f.c == val3) ||
                                  (f => f.A == val4 && f.b == val5 && f.c == val6))

Or, which is preferable IMO:

var predicate = PredicateBuilder.False<Foo>();
predicate = predicate.Or(f => f.A == val1 && f.A == val2 && f.A == val3);
predicate = predicate.Or(f => f.A == val4 && f.A == val5 && f.A == val6);
var foo = db.Foos.Where(predicate);

These can be conditional also:

var predicate = PredicateBuilder.False<Foo>();
predicate = predicate.Or(f => f.A == val1 && f.A == val2 && f.A == val3);
if (condition)
    predicate = predicate.Or(f => f.A == val4 && f.A == val5 && f.A == val6);
var foo = db.Foos.Where(predicate);


来源:https://stackoverflow.com/questions/5904704/how-to-create-sql-nested-ands-inside-of-multiple-ors-using-linq

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