繁体   English   中英

从SqlDataReader访问命令对象

[英]Access command object from SqlDataReader

有一个SqlDataReader对象,我试图获取其相关命令的超时。 例如,我正在使用它来创建我的SqlDataReader

  SqlCommand myCommand = new SqlCommand(query, some_connection);
  _reader = myCommand.ExecuteReader();

在运行时,使用可视化调试器,我可以使用以下命令进行访问:

 _reader.Command.CommandTimeout // Visual debugger 

否,如何在我的代码中访问此“属性”(我想将其作为第三方lib的属性公开)?

内容

我正在从第三个库访问阅读器,因此实际上我只能访问阅读器。 我的问题是要了解为什么我可以在调试器中而不是作为属性来访问命令? 幕后的机制是什么,一些属性扩展,反射?

您将需要使用Reflection来保留Command属性,因为该属性设置为internal访问。 这就是调试器用来向您显示属性的内容。

PropertyInfo prop = _reader.GetType().GetProperty("Command",
    BindingFlags.NonPublic | BindingFlags.Instance);

DbCommand cmd = (DbCommand)prop.GetValue(_reader);
int timeout = cmd.CommandTimeout;

PS:您实际上不应该对第三方组件进行单元测试-就像说“我不信任.NET框架来完成它的工作一样,因此我将检查它在内部所做的所有事情”。 如果要测试它,请将单元测试放在第三方解决方案中。

我建议为SqlCommand和SqlConnection提供外观(包装)。 然后将此对象传递给第三方库。

public class MyOwnReader : IDisposable
{
    bool isDisposed = false;

    SqlConnection _connection;
    SqlCommand _command;


    // You can expose the whole command, or specific property of the command
    public SqlCommand Command
    {
        get
        {
            return _command;
        }
    }


    public MyOwnReader(string connectionString)
    {
        _connection = new SqlConnection(connectionString);
        _connection.Open();
        _command = new SqlCommand();
        _command.Connection = _connection;
        _command.CommandType = CommandType.StoredProcedure; //example initialization
    }

    public void Dispose()
    {
        if (!isDisposed)
        {
            _connection.Dispose();
            _command.Dispose();

            isDisposed = true;
        }
    }

    public SqlDataReader ExecuteReader()
    {
        return _command.ExecuteReader();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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