Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to join multiple WHERE clauses together in SqlKata?

Tags:

c#

.net

sql

sqlkata

I am using SqlKata to creating dynamic SQL queries. I have a list of conditions, stored in my database, which are generated according to my business rules. this is my code sample:

var list = new List<Query>();
foreach(var rule in rules){
    var q = new Query()
       .Where(x=> x.Where("Price", "<", rule.Price).OrWhere("GoodsType", "=", rule.Type));
    list.Add(q);
}

Now I want to join this list item together but none of Where() extensions overload accepts Query type parameters. Is there a way to join the where clauses together?

this is A VERY LITTLE PART OF expected query which I need to generate.

select * from ship_schedule where Path = @path and scheduleDate= @Date
AND (FD.IssueType ='O' OR fd.Path!='ILMTOP' OR  (fd.Path='ILMTOP' AND F.carrier !='MAL'))
AND (FD.IssueType ='O' OR fd.Path!='TOPILM' OR  (fd.Path='ILMTOP' AND F.carrier !='MAL'))

I need to create the second line of the query to the end.

like image 908
Navid_pdp11 Avatar asked May 29 '18 18:05

Navid_pdp11


People also ask

Can you join two SQL queries?

Sometimes you might want to list the records from one table or query with those from one or more other tables to form one set of records - a list with all the records from the two or more tables. This is the purpose of a union query in Access.

Does SqlKata use Dapper?

SqlKata provide an easy way to execute your queries, by using the famous package Dapper.

What is SqlKata?

SqlKata supports complex queries, such as nested conditions, selection from SubQuery, filtering over SubQueries, Conditional Statements and others. Currently it has built-in compilers for SqlServer, MySql, PostgreSql and Firebird. The SqlKata.


1 Answers

The Where method is additive and calling it multiple times will add multiple conditions to the query, so you don't need to build the list of conditions by yourself.

var query = new Query("ship_schedule").Where("Path", path);

foreach(var rule in rules) {
  // loop over rules and append them to the query

  if(col == null) {

    query.WhereNull(col);

  } else {

    query.Where(q => 
      q.Where("Price", "<", rule.Price)
        .OrWhere("GoodsType", "=", rule.Type)
    )

  }
}

Other ways

using the When method

query.When(condition, q => q.Where(...));

using the WhereIf method

query.WhereIf(condition, "Id", "=", 10);
like image 133
amd Avatar answered Oct 17 '22 06:10

amd