/// <summary> /// Creates the query for updating data in the datasource. /// </summary> /// /// <returns> /// Generated Update query. /// </returns> private string CreateUpdateString() { string tableName = GetType().Name; StringBuilder stringBuilder = new StringBuilder($"UPDATE [{tableName}]{Environment.NewLine}SET "); foreach (PropertyInfo property in SchemaFieldProperties.Where(pi => !pi.GetCustomAttribute <SchemaField>().IsPrimaryKey)) { stringBuilder.Append($"[{property.Name}] = @{property.Name}"); if (!property.Name.Equals(SchemaFieldProperties.Last().Name)) { stringBuilder.Append($", "); } } stringBuilder.Append($"{Environment.NewLine}WHERE {PrimaryKeyPropertyInfo.Name} = {PrimaryKeyPropertyInfo.GetValue(this)}"); return(stringBuilder.ToString()); }
/// <summary> /// Deletes the <seealso cref="DBObject"/> from the datasource. /// </summary> /// /// <example> /// The following example shows how to <see cref="Delete"/> a <seealso cref="Customer"/> with a username of "billy123" from the datasource. /// <code> /// DBObject.GetAllRecords<"Customer">().Where(cust => cust.Username == "billy123").FirstOrDefault().Delete(); /// </code> /// </example> /// /// <example> /// The following example shows an alternative way to <see cref="Delete"/> a <seealso cref="Customer"/> with a username of "billy123" from the datasource. /// <code> /// List<Customer> customers = DBObject.GetAllRecords<Customer>(); /// customers.Where(cust => cust.Username == "billy123").FirstOrDefault().Delete(); /// </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 bool Delete() { using (OleDbConnection dbConnection = new OleDbConnection(CONNECTION_STRING)) { string table = GetType().Name; string query = $"DELETE FROM {table} WHERE {PrimaryKeyPropertyInfo.Name} = {PrimaryKeyPropertyInfo.GetValue(this)}"; 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); } }