Is there a way to create one DAO class like EmployeeDAO and this class should be able to work with SQL Server, MySql and MongoDB. It should somehow change and work with MySqlConnection/SqlConnection and MySqlCommand/SqlCommand. 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.
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();
}
}