Dapper SqlBuilder orWhere using AND instead of OR

I tried using the Where and OrWhere methods for SqlBuilder for Dapper, but it does not work as I expected.

The edited part of this question is basically what I came across. Since he did not receive an answer, I will ask him here.

var builder = new SqlBuilder(); var sql = builder.AddTemplate("select * from table /**where**/ "); builder.Where("a = @a", new { a = 1 }) .OrWhere("b = @b", new { b = 2 }); 

I was expecting select * from table WHERE a = @a OR b = @b

but I got select * from table WHERE a = @a AND b = @b

Is it possible to add OR to the where clause using SqlBuilder?

I think this is just a matter of changing the next in the SqlBuilder class to say OR instead of AND, but I wanted to confirm.

 public SqlBuilder OrWhere(string sql, dynamic parameters = null) { AddClause("where", sql, parameters, " AND ", prefix: "WHERE ", postfix: "\n", IsInclusive: true); return this; } 
+6
source share
2 answers

Nevermind I looked at the SqlBuilder code and found that if there is a mixture of Where and OrWhere, it will do the following:

  • Join all the offers of AND
  • Join all OR offers separately
  • Attach OR clauses at the end of AND clauses with AND

If you have no more than 1 OrWhere, you will not see any OR.

I will change my query logic to take this into account

+5
source

You must change your request to:

 var builder = new SqlBuilder(); var sql = builder.AddTemplate("select * from table /**where**/ "); builder.OrWhere("a = @a", new { a = 1 }) .OrWhere("b = @b", new { b = 2 }); 
0
source

All Articles