using System; using System.Collections.Generic; using Microsoft.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace bnhtrade.Core.Data.Database { /// /// Step 1: Call the methods for each where clause you want to create. This can be done multiple times to create an sql where string. Pay attention /// to the prefixes that you'll require between each where clause, as each time a method is called the sql statement will be appended to the previous sql /// string. /// Step 2: Appened the created sql string to your sql statement, NB the WHERE statemet is not included by default. /// Step 3: Once you've created your sql command object, add the parameters to it using the method contained within this class. /// STep 4: exceute your sql commend. /// public class SqlWhereBuilder { private int parameterCount = 0; public SqlWhereBuilder() { Init(); } public string SqlWhereString { get; private set; } public bool IsSetSqlWhereString { get { if (SqlWhereString == null || string.IsNullOrEmpty(SqlWhereString)) { return false; } else { return true; } } } public Dictionary ParameterList { get; private set; } /// /// Initialises the class /// public void Init() { parameterCount = 0; SqlWhereString = ""; ParameterList = new Dictionary(); } public void AddParametersToSqlCommand(SqlCommand cmd) { if (ParameterList != null) { foreach (var item in ParameterList) { cmd.Parameters.AddWithValue(item.Key, item.Value); } } } /// /// Append an 'In' statement and parameter list to the class properties /// /// Name of the column to used to for the condition statement /// List of values to test in condition statement /// Optional prefix that gets added to the sql string result public void In(string columnReference, List orValueList, string wherePrefix = null) { if (orValueList == null || !orValueList.Any()) { return; } var distinctList = orValueList.Distinct().ToList(); string sqlWhere = @" "; if (wherePrefix != null) { sqlWhere += wherePrefix; } sqlWhere += " " + columnReference + " IN ( "; int listCount = distinctList.Count(); for (int i = 0; i < listCount; i++, parameterCount++) { if (i > 0) { sqlWhere += ", "; } string param = "@parameter" + parameterCount; sqlWhere += param; ParameterList.Add(param, distinctList[i]); } sqlWhere += " ) "; SqlWhereString = SqlWhereString + sqlWhere; } /// /// Append an 'In' statement and parameter list to the class properties /// /// Name of the column to used to for the condition statement /// List of values to test in condition statement /// Optional prefix that gets added to the sql string result public void In(string columnReference, List orValueList, string wherePrefix = null) { var stringList = new List(); if (orValueList != null || !orValueList.Any()) { foreach (int value in orValueList) { stringList.Add(value.ToString()); } } In(columnReference, stringList, wherePrefix); } } }