diff --git a/MySqlPlus/MySqlCommandExtensions.cs b/MySqlPlus/MySqlCommandExtensions.cs index 4acefd6..99c393c 100644 --- a/MySqlPlus/MySqlCommandExtensions.cs +++ b/MySqlPlus/MySqlCommandExtensions.cs @@ -1,10 +1,8 @@ using MySql.Data.MySqlClient; using System; -using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; -using System.Threading.Tasks; namespace MontoyaTech.MySqlPlus { @@ -211,6 +209,56 @@ namespace MontoyaTech.MySqlPlus command.CommandText = $"SELECT * FROM `{(rowAttribute == null || string.IsNullOrWhiteSpace(rowAttribute.Name) ? rowType.Name : rowAttribute.Name)}`"; } + /// + /// Setups this MySqlCommand to see if a row exists by an id from the db. + /// + /// + /// + /// + public static void Exists(this MySqlCommand command, ulong 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 EXISTS(SELECT 1 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 see if a row exists by an id from the db. + /// + /// + /// + /// + public static void Exists(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 EXISTS(SELECT 1 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 delete a row from the db by it's id from an instance of the row. /// diff --git a/MySqlPlus/MySqlPlus.csproj b/MySqlPlus/MySqlPlus.csproj index daebfe3..d37ab84 100644 --- a/MySqlPlus/MySqlPlus.csproj +++ b/MySqlPlus/MySqlPlus.csproj @@ -7,7 +7,7 @@ MontoyaTech.MySqlPlus MontoyaTech.MySqlPlus MontoyaTech.MySqlPlus - 1.1.2 + 1.1.3 MontoyaTech A simple C# library to help work with MySql. MontoyaTech 2023