title: One DAO class for access a database in SQL server, MySQL and MongoDB
body: <p>Is there a way to create one DAO class like EmployeeDAO and this class should be able to work with <code>SQL Server</code>, <code>MySql</code> and <code>MongoDB</code>. It should somehow change and work with <code>MySqlConnection/SqlConnection</code> and <code>MySqlCommand/SqlCommand</code>. Right now, I have to create three classses for each database. Are there any interfaces that I can use? I could not find any. Thank you.</p>
  
  <pre><code>public abstract class DaoFactory
  {
    public static DaoFactory GetInstance(DaoConnection daoConnection)
      {
          DaoFactory instance = null;
  
          switch (daoConnection)
          {
                  case DaoConnection.Default:
                  case DaoConnection.MySQL:
              {
                  instance = new MySqlConnectionFactory(MySqlServer, MySqlPort, MySqlUser, MySqlPassword);
                  break;
              }
          }
  
          return instance;
      }
  
   protected string ConnectionString { get; set; }
  
   public abstract DbConnection GetConnection();
  
  }
  
  public class MySqlConnectionFactory : DaoFactory
  {
      public MySqlConnectionFactory(string server, string port, string user, string password) : base(server, port, user, password)
      {
          this.ConnectionString = string.Format("Server={0}; Port={1} Uid={2}; Pwd={3}; pooling=true", server, port, user, password);
      }
  
      public override DbConnection GetConnection()
      {
          return new MySqlConnection(this.ConnectionString);
      }
  }
  
  
  public class EmployeeDao : IEmployeeDao
  {
      private const string InsertEmployee = "INSERT INTO employees VALUES (@name,@age)";
  
      private DaoFactory daoFactory;
  
      EmployeeDao(DaoFactory daoFactory)
      {
          this.daoFactory = daoFactory;
      }
  
      public void Insert(Employee employee)
      {
          MySqlConnection connection =  (MySqlConnection) this.daoFactory.GetConnection();
  
          using (connection)
          {
              var commannd = new MySqlCommand(InsertEmployee, connection);
              commannd.ExecuteNonQuery();
  
          }
      }
  </code></pre>