Factory Pattern Database connection

Viewed 13385

I am trying to implement factory pattern on database connection using MySQL, SQL Server facing weird error

Object reference not set to an instance of an object

on SQL command object

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;
            }
    }
}

Database factory section :

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;
            }
}

Main method

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();
}

and the selection of database by Enum.

2 Answers
Related