简体   繁体   中英

How can I create IDataParameter in a function and return it?

I don't know how this question is correct but my project condition is that I need a function that get value and parameter name and return a Parameter for using in some commands.
The prototype that I am thinking on it is like this :

public IDataParameter CreateParameter(string parameterName, object value)

Is this anyway to do that ?

Thanks to @nvoigt I created a class for it that derivative from IDBDataParameter
I added two constructor based on my requirement.

public class MyClass: IDbDataParameter
{
    public MyClass(string parameterName, object value)
    {
        ParameterName = parameterName;
        Value = value;
    }
    public MyClass(string parameterName, object value, DbType dbType)
    {
        ParameterName = parameterName;
        Value = value;
        DbType = dbType;
    }
    public DbType DbType { get; set; }
    public ParameterDirection Direction { get; set; }
    public bool IsNullable => throw new NotImplementedException();
    public string ParameterName { get; set; }
    public string SourceColumn { get; set; }
    public DataRowVersion SourceVersion { get; set; }
    public object Value { get; set; }
    public byte Precision { get; set; }
    public byte Scale { get; set; }
    public int Size { get; set; }
}


and use them in a method like this :

public IDbDataParameter CreateParameter(string parameterName, object value)
    {
        return new MyClass(parameterName, value);
    }


While you certainly can do that, it would mean you'd need to hard code into your function which class you want to instantiate for your return value.

Better would be to pass in the commands, because they should know what type of parameter they need.

Example:

public IDbDataParameter CreateParameter(IDbCommand command, string parameterName, object value)
{
    var parameter = command.CreateParameter();

    parameter.ParameterName = parameterName;
    parameter.Value = value;

    return parameter;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM