[英]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. 我正在使用SQLBase NET数据提供程序。
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. SQLBaseDatabase
类是我编写的包装器,基本上将返回一个连接并创建一个命令。
var db = new SQLBaseDatabase(ConfigurationManager.ConnectionStrings["UDSConnectionString"].ConnectionString);
This code works: I created this code in my HomeController
as a test. 这段代码有效:我在
HomeController
创建了此代码作为测试。 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. 我不确定我是否从根本上在c#中做错了可能导致此错误的错误。 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. **更新** SqlServer ADO.Provider发生相同的问题。
I would try initializing the SQLBaseCommand in your method the same way you did in the first example. 我将尝试以与第一个示例相同的方式在您的方法中初始化SQLBaseCommand。
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.
例如,Parameters属性可能不会隐式更新。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.