From 926fff38fd03d948af28136831d7702129a8c759 Mon Sep 17 00:00:00 2001 From: MattMo Date: Tue, 13 Jun 2023 15:10:51 -0700 Subject: [PATCH] Added extension functions for getting a row by a string id, and deleting a row by a string id. --- MySqlPlus/MySqlCommandExtensions.cs | 59 +++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/MySqlPlus/MySqlCommandExtensions.cs b/MySqlPlus/MySqlCommandExtensions.cs index e8d10e6..4acefd6 100644 --- a/MySqlPlus/MySqlCommandExtensions.cs +++ b/MySqlPlus/MySqlCommandExtensions.cs @@ -169,6 +169,31 @@ namespace MontoyaTech.MySqlPlus command.Parameters.AddWithValue("@id", id); } + /// + /// Setups this MySqlCommand to get a row from the db by a string id. + /// + /// + /// + /// + public static void Get(this MySqlCommand command, string id) + { + //Get the type of T + var rowType = typeof(T); + + //Get the row information. + var rowAttribute = rowType.GetCustomAttribute(); + + //Get the id field + if (!rowType.GetMySqlPrimaryKey(out FieldInfo primaryField, out MySqlColumn primaryColumn)) + throw new Exception("Failed to find the primary key for the given row."); + + //Set the command text. + command.CommandText = $"SELECT * FROM `{(rowAttribute == null || string.IsNullOrWhiteSpace(rowAttribute.Name) ? rowType.Name : rowAttribute.Name)}` WHERE `{(string.IsNullOrWhiteSpace(primaryColumn.Name) ? primaryField.Name : primaryColumn.Name)}`=@id LIMIT 1"; + + //Add the id parameter. + command.Parameters.AddWithValue("@id", id); + } + /// /// Setups this MySqlCommand to get all the rows of a given type from the db. /// @@ -255,6 +280,40 @@ namespace MontoyaTech.MySqlPlus command.CommandText = builder.ToString(); } + /// + /// Setups this MySqlCommand to delete a row from the db by it's string id. + /// + /// + /// + /// + public static void Delete(this MySqlCommand command, string id) + { + //Get the type of T + var rowType = typeof(T); + + //Get the row information. + var rowAttribute = rowType.GetCustomAttribute(); + + //Start building the query. + var builder = new StringBuilder(); + + //Write the delete from section + builder.Append($"DELETE FROM `{(rowAttribute == null || string.IsNullOrWhiteSpace(rowAttribute.Name) ? rowType.Name : rowAttribute.Name)}` "); + + //Get the primary key field and column. + if (!rowType.GetMySqlPrimaryKey(out FieldInfo primaryField, out MySqlColumn primaryColumn)) + throw new Exception("Failed to find primary key for the given row."); + + //Write the where clause + builder.Append($"WHERE `{(string.IsNullOrWhiteSpace(primaryColumn.Name) ? primaryField.Name : primaryColumn.Name)}`=@id LIMIT 1"); + + //Add the id parameter. + command.Parameters.AddWithValue("@id", id); + + //Set the command text. + command.CommandText = builder.ToString(); + } + /// /// Setups this MySqlCommand to delete all rows of a given type from the db. ///