Md Ghousemohi
Md Ghousemohi

Reputation: 197

ExecuteReader: Connection property has not been initialized. while im using abstract class connection

Here i'm using connection state in abstract class

  public abstract class Connection
    {
        private static string _Connection = ConfigurationManager.ConnectionStrings["CTXDB"].ConnectionString;
 public static string GetConnection{ get { return _Connection; }}
}
    public abstract void ProcessConnection();

This class i implemented in Another class(BusinessConnection.cs)

 public class BusinessClass :Connection
    {
     public override void ProcessConnection()
            {
                using (var conn = new SqlConnection(Connection.GetConnection))
                {
                    conn.Open();
                }
            }

Now i called this Class(BusinessConnection.cs) In my controller as

     BusinessClass objcon = new BusinessClass();   
  public IHttpActionResult Index()
                    objcon.ProcessConnection();
                    SqlCommand cmd = new SqlCommand("select * from Employee");
//Here how can i inject my Connection in cmd
                    SqlDataReader rdr = cmd.ExecuteReader();
                    if (rdr.HasRows == true)

Upvotes: 0

Views: 38

Answers (1)

René Vogt
René Vogt

Reputation: 43906

There seems to be a little design flaw. You obviously want to use the connection outside the BusinessClass/Connection classes.

So maybe you can do something like this:

public abstract class Connection
{
    public abstract SqlConnection OpenConnection();

    // your code
}

and in your BusinessClass:

public override SqlConnection OpenConnection()
{
     var conn = new SqlConnection(Connection.GetConnection))
     conn.Open();
     return conn;
}

And then in your querying code:

using(SqlConnection conn = objcon.OpenConnection())
{
    // create SqlCommand and pass conn!
    using(SqlCommand cmd = new SqlCommand("select * from Employee", conn))
    {
        using (SqlDataReader rdr = cmd.ExecuteReader())
        {
        // and the rest of your rdr reading code
        }
    }
}

The using statements take care of closing/disposing the respective objects.

Upvotes: 2

Related Questions