DbExtensions - Add Where clause with multiple OR clauses

467 Views Asked by At

New to DbExtensions (just this morning), now i have an SQL statement that looks something like this

SELECT * FROM myTable
WHERE (Field1 LIKE @Word)
    OR (Field2 LIKE @Word)
    OR (Field3 LIKE @Word)
    OR (Field4 LIKE @Word)
    OR (Field5 LIKE @Word)

I cannot work out how to do this using DbExtensions?

This is what i have so far

var query = SQL
    .FROM("myTable")
    .WHERE();

query.AppendClause("OR", ",", "Field1 LIKE {0}", new string[] { term });
query.AppendClause("OR", ",", "Field2 LIKE {0}", new string[] { term });
query.AppendClause("OR", ",", "Field3 LIKE {0}", new string[] { term });
query.AppendClause("OR", ",", "Field4 LIKE {0}", new string[] { term });
query.AppendClause("OR", ",", "Field5 LIKE {0}", new string[] { term });

But will this not add lots of parameters, which there is only 1 value for. Maybe i am missing something?

1

There are 1 best solutions below

1
On
var predicate = new StringBuilder();
var parameters = new List<object>();

for (int = 0; i < words.Length; i++) {
   if (i > 0) {
      predicate.Append(" OR ");
   }
   predicate.AppendFormat("({0} LIKE {{{1}}})", GetFieldName(i), i);
   parameters.Add(words[i]);
}

var query = SQL
    .FROM("myTable")
    .WHERE("(" + predicate.ToString() + ")", parameters.ToArray());