private void Insert(IBenchmarkObject benchmarkObject, string parentFkColumn, object parentFkValue) { // Create table or add columns. DbTableInfo tableInfo = benchmarkObject.GetTableInfo(); SyncDbStructure(tableInfo); Type type = benchmarkObject.GetType(); SqlCommand cmd = CreateCommand(); // Prepare command. string insert = string.Format("INSERT INTO [{0}].[{1}] (", Schema, tableInfo.TableName); string values = "VALUES ("; bool first = true; bool autoIncPk = false; object pkValue = null; foreach (DbColumnInfo columnInfo in tableInfo.DbColumns) { // Skip auto-incremented values. if (columnInfo.DbAutoIncrement) { autoIncPk = true; continue; } // Skip values for which we do not have a property or they do not match the parent table. object value = null; if (columnInfo.DbColumn == parentFkColumn) { value = parentFkValue; } else { if (columnInfo.Property != null) { PropertyInfo propertyInfo = type.GetProperty(columnInfo.Property); if (propertyInfo != null) { value = propertyInfo.GetValue(benchmarkObject); } } } if (value == null) { continue; } if (columnInfo.DbPrimaryKey) { pkValue = value; } if (!first) { insert += ", "; values += ", "; } string paramName = "@" + columnInfo.DbColumn; value = ConvertValue(value); if (value is string) { AdjustColumnMaxLength(tableInfo, columnInfo, (string)value); } insert += string.Format("[{0}]", columnInfo.DbColumn); values += paramName; cmd.Parameters.AddWithValue(paramName, value); first = false; } insert += ")"; values += ")"; cmd.CommandText = insert + Environment.NewLine + values; // Run the command. cmd.ExecuteNonQuery(); // Retrieve scope identity. if (autoIncPk) { SqlCommand cmdGetIdentity = CreateCommand(); cmdGetIdentity.CommandText = "SELECT IDENT_CURRENT(@fullTableName)"; cmdGetIdentity.Parameters.AddWithValue("fullTableName", string.Format("[{0}].[{1}]", Schema, tableInfo.TableName)); pkValue = cmdGetIdentity.ExecuteScalar(); } // Insert recursive. foreach (Benchmark.DbDependentTableInfo dependentTable in tableInfo.DbDependentTables) { PropertyInfo propertyInfo = type.GetProperty(dependentTable.Property); if (propertyInfo != null) { object collection = propertyInfo.GetValue(benchmarkObject); if (collection is IEnumerable e) { foreach (IBenchmarkObject childObject in e) { Insert(childObject, dependentTable.DbFkColumn, pkValue); } } } } }