簡體   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