lundi 29 mai 2017

Factory Pattern Database connection

I am trying to implement factory pattern on Database Connection using MYSQL , SQLSERVER facing wired 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.

Aucun commentaire:

Enregistrer un commentaire