/// <summary> /// Deletes the <seealso cref="DBObject"/> from the datasource. /// </summary> /// <param name="dbObject"><seealso cref="DBObject"/> to delete from the datasource.</param> /// /// <example> /// The following example shows how to <see cref="Delete"/> a <seealso cref="Customer"/> with a username of "billy123" from the datasource. /// <code> /// List<Customer> customers = DBController.GetAllRecords<Customer>().Where(cust => cust.Username == "billy123").ToList(); /// foreach (Customer customer in customers) /// DBController.Delete(customer); /// </code> /// </example> /// /// <returns> /// Whether the delete was successful or not. /// </returns> /// <exception cref="OleDbException"> /// Throws an exception when a foreign key linkage is being violated. /// </exception> public static bool Delete(DBObject dbObject) { using (OleDbConnection dbConnection = new OleDbConnection(CONNECTION_STRING)) { string table = dbObject.GetType().Name; string query = $"DELETE FROM {table} WHERE {dbObject.PrimaryKeyPropertyInfo.Name} = {dbObject.PrimaryKey}"; int rowsAffected; using (OleDbCommand command = new OleDbCommand(query, dbConnection)) { dbConnection.Open(); try { rowsAffected = command.ExecuteNonQuery(); } catch (OleDbException ex) { Console.Error.WriteLine(ex.Message); throw; } } return(rowsAffected != 0); } }
/// <summary> /// Adds a parameter to the <paramref name="command"/> using the value of the <paramref name="property"/>. /// </summary> /// <param name="command">Command to execute against the datasource.</param> /// <param name="property"><seealso cref="PropertyInfo"/> of which a value will be attained.</param> /// <param name="dbObject"><seealso cref="DBObject"/> to get the <paramref name="property"/> value from.</param> private static void AddParameterToCommandFromProperty(OleDbCommand command, PropertyInfo property, DBObject dbObject) { object value = property.GetValue(dbObject); // Used to say .GetValue(this) string name = $"@{property.Name}"; command.Parameters.AddWithValue(name, value); }
/// <summary> /// Adds values to the <seealso cref="PropertyInfo"/> placeholders nested in the generated query. /// </summary> /// <param name="command">Command to execute against the datasource.</param> /// <param name="saveType">Specifies how to save the <seealso cref="DBObject"/></param> /// <param name="dbObject"><seealso cref="DBObject"/> to get information from.</param> private static void AddValuesToPropertyPlaceholders(OleDbCommand command, SaveTypes saveType, DBObject dbObject) { IEnumerable <PropertyInfo> propertyList = dbObject.SchemaFieldProperties; if (saveType == SaveTypes.Update) { propertyList = propertyList.Where(pi => !pi.GetCustomAttribute <SchemaField>().IsPrimaryKey); } foreach (PropertyInfo property in propertyList) { AddParameterToCommandFromProperty(command, property, dbObject); } }