KWallace
KWallace

Reputation: 1698

c# How to create a Method on a Method, or Method Chain

I have created a simplified SQL Data class, and a class method for returning a ready to use resultset:

public SQL_Data(string database) {

    string ConnectionString = GetConnectionString(database);

    cn = new SqlConnection(ConnectionString);

    try {
        cn.Open();
    } catch (Exception e) {
        Log.Write(e);
        throw;
    }

}

public SqlDataReader DBReader(string query) {

    try {

        using (SqlCommand cmd = new SqlCommand(query, this.cn)) {
            return cmd.ExecuteReader(CommandBehavior.CloseConnection);
        }

    } catch {

        Log.Write("SQL Error with either Connection String:\n" + cn + " \nor Query:\n" + query);
        throw;
    }

}

(I catch any errors, log them, and then catch the error higher up the chain. Also, I did not include the ConnectionString() code for brevity. It just returns the requested connection string. That's all.)

This all works just fine, and with a single line of code, I'm ready to .Read() rows.

SqlDataReader rs = new SQL_Data("MyDatabase").DBReader(@"SELECT * FROM Employees");

while (rs.Read()) {
    // code
}

rs.Close();

I want to expand this and add a .ColumnReader() method that I want to chain to .DBReader() like this:

string empID = new SQL_Data("MyDatabase").DBReader(@"SELECT * FROM Employees).ColumnReader("EmpID");

I attempted this by adding a .ColumnReader() method, but it ends up being a method of SQL_Data() class directly, not a member or extension of .DBReader(). I also tried adding the .ColumnReader() inside the .DBReader() (like a "closure"), but that didn't work either.

Can this be done?

Upvotes: 0

Views: 170

Answers (1)

KWallace
KWallace

Reputation: 1698

This ended up working for me:

public static class SQLExtentions {

    public static dynamic ColumnReader(this SqlDataReader rs, string colName) {
        return rs[colName];
    }

}

I will have to expand on it a bit to add some error checking, and perhaps return more than just the dynamic value - like return an object with the value and it's SQL data type. But Paul and Bagus' comments got me on the right track.

Upvotes: 1

Related Questions