示例#1
0
    public static void Update <T>(this ISqlConnectionProvider sqlConnectionProvider,
                                  T objectToUpdate,
                                  Expression <Func <T, object> > keyProperties = null,
                                  string tableName        = null,
                                  string schemaName       = null,
                                  bool processColumnNames = true)
    {
        tableName = SqlTextFunctions.GetTableName(objectToUpdate.GetType(), tableName, schemaName);

        using (var myConnection = sqlConnectionProvider.ToSqlConnection())
        {
            using (var myCommand = new SqlCommand {
                Connection = myConnection
            })
            {
                var setClauseProperties   = SqlClrHelpers.GetRelevantPropertyInfos(objectToUpdate, null);
                var whereClauseProperties = SqlClrHelpers.GetPropertiesFromObject(objectToUpdate, keyProperties);
                SqlTextFunctions.UnUnderscoreColumnNames = processColumnNames;
                BuildOutUpdateCommand(objectToUpdate,
                                      tableName,
                                      setClauseProperties,
                                      whereClauseProperties,
                                      myCommand,
                                      processColumnNames);
                SqlTextFunctions.UnUnderscoreColumnNames = true;
                myConnection.Open();
                SqlLogger.LogSqlCommand(myCommand);
                myCommand.ExecuteNonQuery();
                myConnection.Close();
            }
        }
    }
    private static void BuildOutMyCommand <T>(T objToDelete, Expression <Func <T, object> > keyProperties, string tableName, SqlCommand myCommand)
    {
        var whereClauseProperties     = SqlClrHelpers.GetPropertiesFromObject(objToDelete, keyProperties);
        var whereClauseColumnNames    = whereClauseProperties.Select(SqlTextFunctions.GetColumnNameFromPropertyInfo).ToList();
        var whereClauseParameterNames = whereClauseProperties.Select(SqlTextFunctions.GetParameterName).ToList();
        var whereClauseParts          = Enumerable
                                        .Range(0, whereClauseColumnNames.Count)
                                        .Select(index => $"{whereClauseColumnNames[index]} = {whereClauseParameterNames[index]}");
        var whereClause = string.Join(" AND ", whereClauseParts);

        var whereClauseParameters = Enumerable
                                    .Range(0, whereClauseProperties.Count)
                                    .Select(
            index => SqlTextFunctions.GetParameter(objToDelete, whereClauseProperties[index], whereClauseParameterNames[index]))
                                    .ToList();

        myCommand.Parameters.AddRange(whereClauseParameters.ToArray());
        myCommand.CommandText = $"DELETE FROM {tableName} WHERE {whereClause}";
    }