简体   繁体   中英

Ado.net data provider is throwing an error when I try to return a command from a method

I'm sorry for the bad title, not certain how to describe the issue completely.

I'm using SQLBase NET data provider.

When I attempt to create a command and add parameters, it is throwing an exception

Object not set to instance of an object

However, when I create a command outside of my object, I can add parameters with no issues.

SQLBaseDatabase class is a wrapper I wrote that will basically return a connection and create a command.

var db = new SQLBaseDatabase(ConfigurationManager.ConnectionStrings["UDSConnectionString"].ConnectionString);

This code works: I created this code in my HomeController as a test. I can add parameters with no problem.

var command = new SQLBaseCommand();
command.Connection = db.GetConnection() as SQLBaseConnection;
command.Parameters.Add(db.GetParameter(":1", "1234", DbType.String));

This code fails:

var parameters = new List<IDataParameter>();
parameters.Add(db.GetParameter(":1", "1234", DbType.String));
var cmd = db.GetCommand(db.GetConnection(), "Select * From DX_CODES Where (DX = :1)", parameters);

When I try to add parameters in this method via the passed in parameters, it throws the object not set error.

public IDbCommand GetCommand(IDbConnection connection, string sql, IEnumerable<IDataParameter> parameters)
{
    var command = new SQLBaseCommand(connection as SQLBaseConnection);            

    foreach (var parameter in parameters)
        command.Parameters.Add(parameter); // This throws an error. Command.Parameters is read only.

    command.CommandText = sql;

    return command;
}

The command parameters is read only

Here is my method that creates the parameter

 public IDbDataParameter GetParameter(string name, object value, DbType type)
 {
     return new SQLBaseParameter(name, type, value);
 }

I'm not sure if I'm fundamentally doing some wrong in c# that could be causing this error. Or how I can fix it considering it works in one case, but not the other.

** Update ** Same issue happens with the SqlServer ADO.Provider.

I would try initializing the SQLBaseCommand in your method the same way you did in the first example.

var command = new SQLBaseCommand();    
command.Connection = connection as SQLBaseConnection;

There could be a very different implementation of that constructor with and without constructor parameters. For example, the Parameters property may not get newed implicitly.

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