private SqlCommand CreateUpdateCommand (DataRow row, DataTableMapping tableMapping)
{
// If no table was found, then we can't do an update
if (QuotedTableName == String.Empty)
return null;
CreateNewCommand (ref updateCommand);
string command = String.Format ("UPDATE {0} SET ", QuotedTableName);
StringBuilder columns = new StringBuilder ();
StringBuilder whereClause = new StringBuilder ();
int parmIndex = 1;
string dsColumnName = String.Empty;
bool keyFound = false;
// First, create the X=Y list for UPDATE
foreach (DataRow schemaRow in dbSchemaTable.Rows) {
if (columns.Length > 0)
columns.Append (" , ");
SqlParameter parameter = updateCommand.Parameters.Add (CreateParameter (parmIndex++, schemaRow));
dsColumnName = tableMapping.ColumnMappings [parameter.SourceColumn].DataSetColumn;
if (row != null)
parameter.Value = row [dsColumnName, DataRowVersion.Proposed];
columns.Append (String.Format ("{0} = {1}", GetQuotedString (parameter.SourceColumn), parameter.ParameterName));
}
// Now, create the WHERE clause. This may be optimizable, but it would be ugly to incorporate
// into the loop above. "Premature optimization is the root of all evil." -- Knuth
foreach (DataRow schemaRow in dbSchemaTable.Rows) {
if (!IncludedInWhereClause (schemaRow))
continue;
if (whereClause.Length > 0)
whereClause.Append (" AND ");
bool isKey = (bool) schemaRow ["IsKey"];
SqlParameter parameter = null;
if (!isKey) {
parameter = updateCommand.Parameters.Add (CreateParameter (parmIndex++, schemaRow));
dsColumnName = tableMapping.ColumnMappings [parameter.SourceColumn].DataSetColumn;
if (row != null)
parameter.Value = row [dsColumnName];
whereClause.Append ("(");
whereClause.Append (String.Format (clause1, GetQuotedString (parameter.SourceColumn), parameter.ParameterName));
whereClause.Append (" OR ");
}
else
keyFound = true;
parameter = updateCommand.Parameters.Add (CreateParameter (parmIndex++, schemaRow));
dsColumnName = tableMapping.ColumnMappings [parameter.SourceColumn].DataSetColumn;
if (row != null)
parameter.Value = row [dsColumnName];
whereClause.Append (String.Format (clause2, GetQuotedString (parameter.SourceColumn), parameter.ParameterName));
if (!isKey)
whereClause.Append (")");
}
if (!keyFound)
throw new InvalidOperationException ("Dynamic SQL generation for the UpdateCommand is not supported against a SelectCommand that does not return any key column information.");
// We're all done, so bring it on home
string sql = String.Format ("{0}{1} WHERE ( {2} )", command, columns.ToString (), whereClause.ToString ());
updateCommand.CommandText = sql;
return updateCommand;
}