Search code examples
c#c#-4.0sqlclient

Create Conversion for derived IDbCommand class


I've created a derived IDbCommand classe that I want to use for easier Sql-DB Access.

internal class Prozedur : IDbCommand
{
    private SqlCommand command = new SqlCommand();
    private SqlConnection connection;
    string commandtext;
    CommandType commandType;
    ...

Now I want to expand this class to handle the value assignment from the output parameters of the sql-procedure to the properties of a local class like this:

Prozedur p = new Prozedur();
object.Name = p.Parameters["@Name"].Value;

This obviously won't work as there is no conversion for this. I know that using

object.Name = (string)p.Parameters["@Name"].Value;

will work. How do I have to expand the Prozedur class, so I will be able to use

object.Name = p.Parameters["@Name"].Value;

and do other stuff like checking the parameter values or check for null values?


Solution

  • Implement a method to access those values and return them already typed:

    public TValue GetValue<TValue>(string parameterName)
    {
        // Do stuff here before returning the parameter value...
        return (TValue)Parameters[$"@{parameterName}"]?.Value;
    }
    

    Later, you'll access your parameters' values as follows:

    string name = proc.GetValue<string>("name");
    

    Other than that... there's another approach on which you would implement a method to get values of specific types:

    public object GetValue(string parameterName)
    {
        // Do common stuff here to any parameter value type
        return Parameters[$"@{parameterName}"]?.Value;
    }
    
    public string GetString(string parameterName)
    {
         // Do common stuff here to string parameters only
         return (string)GetValue(parameterName);
    }