Skip to content

Commit

Permalink
Added ExecuteScalar<T> generics
Browse files Browse the repository at this point in the history
  • Loading branch information
danielgindi committed Jul 22, 2019
1 parent 3042bf7 commit 9ad59b4
Showing 1 changed file with 37 additions and 2 deletions.
39 changes: 37 additions & 2 deletions dg.Sql/Sql/Query/Executes.cs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ public DataReaderBase ExecuteReader(ConnectorBase connection = null)
throw;
}
}

/// <summary>
/// Will execute the query returning the first value of the first row.
/// </summary>
Expand Down Expand Up @@ -99,7 +99,42 @@ public object ExecuteScalar(ConnectorBase connection = null)
}
}
}


/// <summary>
/// Will execute the query returning the first value of the first row.
/// </summary>
/// <typeparam name="T">Type to convert to</typeparam>
/// <param name="connection">An existing connection to use.</param>
/// <returns>a value of the required type, or null if the returned value was null or could not be converted to specified type</returns>
/// <remarks>You might want to limit the query return rows, to optimize the query.</remarks>
public Nullable<T> ExecuteScalarOrNull<T>(ConnectorBase connection = null) where T : struct, IConvertible
{
var scalar = ExecuteScalar(connection);

if (scalar == null || !(scalar is IConvertible)) return null;

var converted = Convert.ChangeType(scalar, typeof(T));
if (converted == null) return null;

return (T)converted;
}

/// <summary>
/// Will execute the query returning the first value of the first row.
/// </summary>
/// <typeparam name="T">Type to convert to</typeparam>
/// <param name="connection">An existing connection to use.</param>
/// <returns>a value of the required type, or null if the returned value was null or could not be converted to specified type</returns>
/// <remarks>You might want to limit the query return rows, to optimize the query.</remarks>
public T ExecuteScalar<T>(ConnectorBase connection = null) where T : class, IConvertible
{
var scalar = ExecuteScalar(connection);

if (scalar == null || !(scalar is IConvertible)) return null;

return Convert.ChangeType(scalar, typeof(T)) as T;
}

/// <summary>
/// Will execute the query without reading any results.
/// </summary>
Expand Down

0 comments on commit 9ad59b4

Please sign in to comment.