title: Factory Pattern Database connection
body: <p>I am  trying to implement factory pattern on database connection using MySQL, SQL Server facing weird error </p>
  
  <blockquote>
    <p>Object reference not set to an instance of an object </p>
  </blockquote>
  
  <p>on SQL command object</p>
  
  <pre><code>internal class SqlServerDB : IDatabase
  {
      private SqlConnection _Connection = null;
      private SqlCommand _Command = null;
  
      public IDbCommand Command
      {
              get
              {
                  if (_Command == null)
                  {
                      _Command.Connection = (SqlConnection)Connection;
  
                      //_Command = new SqlCommand();
                  }
                  return _Command;
              }
      }
  
      public IDbConnection Connection
      {
              get
              {
                  if (_Connection == null)
                  {
                      string connectionString = ConfigurationManager.ConnectionStrings["testSQL"].ConnectionString;
                      _Connection = new SqlConnection(connectionString);
                  }
                  return _Connection;
              }
      }
  }
  </code></pre>
  
  <p>Database factory section :</p>
  
  <pre><code>public static class DatabaseFactory
  {
              public static IDatabase CreateDatabase(DBType type)
              {
                  switch (type)
                  {
                      case DBType.SqlServer:
                          return new SqlServerDB();
  
                      case DBType.MySql:
                          return new MySQLDB();
                  }
  
                  return null;
              }
  }
  </code></pre>
  
  <p>Main method </p>
  
  <pre><code>static void Main(string[] args)
  {
      IDatabase database;
      DBType databaseType = DBType.SqlServer;
  
      database = DatabaseFactory.CreateDatabase(databaseType);
      IDbConnection connection = database.Connection;
  
      IDbCommand command = database.Command;
      command.CommandType = CommandType.Text;
      command.CommandText = "select * from User";
  
      connection.Open();
  }
  </code></pre>
  
  <p>and the selection of database by Enum.</p>