I build a NetCore 3.1 application who use Postgres as database engine, and I have an entity SomeEntity
who contains:
- Id : int
- Name: text
- Tags: text[]
I try to build a filter on the attribute Tags
. It must only select rows where the Tags
array contains one or more elements of an unknown length array argument.
Let's use an example !
We have this SomeEntity
with the data set bellow:
Id | Name | Tags |
---|---|---|
1 | n1 | array ("tag1", "tag2", "tag3") |
2 | n2 | array ("tag2", "tag3") |
3 | n2 | array ("tag3") |
I want to get all rows where the attribute Tags contains the value "Tag1" or "Tag2" (The Tags
can contain more than one values at the same time).
I've tried the code bellow:
List<string> terms = new List<string> { "Tag1", "Tag2" };
IQueryable<FileEntity> query = Context.SomeEntity;
foreach (string term in terms) {
query = query.Where(w => w.Tags.Contains(term));
}
List< SomeEntity > result = query.ToList();
But when you chained the "where" statement with linq, it will result to a list of AND operator. This is the SQL request resulting from the above code.
SELECT f."Id", f."name", f."Tags"
FROM " SomeEntity " AS f
WHERE ((@__andEl_0 = ANY (f."Tags") AND @__andEl_1 = ANY (f."Tags"));
So, how can I build this request with OR operator in place of AND ?