Padrão DAO e VO em C#: Implementação Completa de CRUD

Computer science8.76 KB

Abaixo encontra-se a implementação em C# das classes de persistência, modelo e infraestrutura utilizando os padrões DAO (Data Access Object) e VO (Value Object) com ADO.NET.

Implementação do Padrão DAO em C#

A classe ClienteDAO concentra as instruções SQL de inserção, exclusão, alteração, navegação e consulta de registros da tabela de clientes.

Classe ClienteDAO

class ClienteDAO
{
    public static void Inserir(ClienteVO obj)
    {
        string valor = obj.GetNome().Trim();
        string sql = string.Format(
            "INSERT INTO armacao(id_cliente,nome,endereco,telefone,cidade,email)" +
            "VALUES ({0},'{1}','{2}','{3}','{4}','{5}')",
            obj.GetId(),
            obj.GetNome(),
            obj.GetEndereco(),
            obj.GetTelefone(),
            obj.GetCidade(),
            obj.GetEmail()
        );

        Metodos.ExecutaSQL(sql);
    }

    public static void Excluir(int id)
    {
        string sql = string.Format("DELETE FROM cliente WHERE id_cliente = " + id.ToString());
        try
        {
            Metodos.ExecutaSQL(sql);
        }
        catch
        {
            throw new Exception("Impossível excluir o registro escolhido.");
        }
    }

    public static void Alterar(ClienteVO obj)
    {
        try
        {
            string valor = obj.GetNome().Trim();
            string sql = string.Format(
                "UPDATE cliente SET " +
                "nome = '{0}'," +
                "endereco = '{1}'," +
                "telefone = '{2}'," +
                "cidade = '{3}'," +
                "email = '{4}'",
                obj.GetNome(),
                obj.GetEndereco(),
                obj.GetTelefone(),
                obj.GetCidade(),
                obj.GetEmail()
            );

            Metodos.ExecutaSQL(sql);
        }
        catch
        {
            throw new Exception("Impossível alterar o registro escolhido.");
        }
    }

    public static ClienteVO Consultar(int id)
    {
        string sql = "SELECT * FROM cliente WHERE id_cliente = " + id.ToString();
        DataTable tabela = Metodos.ExecutaSelect(sql);

        if (tabela.Rows.Count == 0)
            return null;
        else
        {
            return MontaVO(tabela.Rows[0]);
        }
    }

    public static ClienteVO Pesquisar(ClienteVO obj)
    {
        string sql = "SELECT * FROM cliente WHERE id_cliente != 0";

        if (obj.GetNome() != "")
        {
            sql += " AND nm_cliente = '" + obj.GetNome() + "'";
        }

        if (obj.GetCidade() != "")
        {
            sql += " AND nm_cidade = '" + obj.GetCidade() + "'";
        }

        if (obj.GetEmail() != "")
        {
            sql += " AND nm_email = '" + obj.GetEmail() + "'";
        }

        if (obj.GetEndereco() != "")
        {
            sql += " AND nm_endereco = '" + obj.GetEndereco() + "'";
        }

        string command = "SELECT * FROM cliente WHERE id_cliente = " + sql.ToString();
        DataTable tabela = Metodos.ExecutaSelect(command);

        if (tabela.Rows.Count == 0)
            return null;
        else
        {
            return MontaVO(tabela.Rows[0]);
        }
    }

    public static ClienteVO MontaVO(DataRow row)
    {
        ClienteVO obj = new ClienteVO();
        obj.SetId(Convert.ToInt32(row["id"]));
        obj.SetNome(row["nome"].ToString());
        obj.SetEndereco(row["endereco"].ToString());
        obj.SetEmail(row["email"].ToString());
        obj.SetTelefone(row["telefone"].ToString());
        obj.SetCidade(row["cidade"].ToString());
        return obj;
    }

    public static ClienteVO Primeiro()
    {
        string sql = "SELECT top 1 * FROM cliente ORDER BY id_cliente ASC";
        DataTable tabela = Metodos.ExecutaSelect(sql);

        if (tabela.Rows.Count == 0)
        {
            return null;
        }
        else
        {
            return MontaVO(tabela.Rows[0]);
        }
    }

    public static ClienteVO Ultimo()
    {
        string sql = "SELECT top 1 * FROM cliente ORDER BY id_cliente DESC";
        DataTable tabela = Metodos.ExecutaSelect(sql);

        if (tabela.Rows.Count == 0)
        {
            return null;
        }
        else
        {
            return MontaVO(tabela.Rows[0]);
        }
    }

    public static ClienteVO Anterior(int id)
    {
        string sql = "SELECT top 1 * FROM cliente WHERE id < " + id + " ORDER BY id_cliente DESC";
        DataTable tabela = Metodos.ExecutaSelect(sql);

        if (tabela.Rows.Count == 0)
        {
            return null;
        }
        else
        {
            return MontaVO(tabela.Rows[0]);
        }
    }

    public static ClienteVO Proximo(int id)
    {
        string sql = "SELECT top 1 * FROM cliente WHERE id > " + id + " ORDER BY id_cliente ASC";
        DataTable tabela = Metodos.ExecutaSelect(sql);

        if (tabela.Rows.Count == 0)
        {
            return null;
        }
        else
        {
            return MontaVO(tabela.Rows[0]);
        }
    }
}

Modelo de Dados com Validações

A classe ClienteVO encapsula os atributos do cliente, contendo regras de validação nos métodos de atribuição (setters).

Classe ClienteVO

class ClienteVO
{
    #region ID
    private int id;

    public void SetId(int valor)
    {
        if (valor <= 0)
            throw new Exception("Id inválido!");
        else
            id = valor;
    }

    public int GetId()
    {
        return id;
    }
    #endregion

    #region NOME
    private string nome;

    public void SetNome(string valor)
    {
        valor = valor.Trim();
        if (valor.Length == 0 || valor.Length > 60)
            throw new Exception("Nome inválido");
        else
            nome = valor;
    }

    public string GetNome()
    {
        return nome;
    }
    #endregion

    #region ENDERECO
    private string endereco;

    public void SetEndereco(string valor)
    {
        valor = valor.Trim();
        if (valor.Length == 0 || valor.Length > 100)
            throw new Exception("Endereço inválido!");
        else
            endereco = valor;
    }

    public string GetEndereco()
    {
        return endereco;
    }
    #endregion

    #region CIDADE
    private string cidade;

    public void SetCidade(string valor)
    {
        valor = valor.Trim();
        if (valor.Length == 0 || valor.Length > 55)
            throw new Exception("Cidade inválida!");
        else
            cidade = valor;
    }

    public string GetCidade()
    {
        return cidade;
    }
    #endregion

    #region EMAIL
    private string email;

    public void SetEmail(string valor)
    {
        valor = valor.Trim();

        if (valor.IndexOf('.') == -1 ||
            valor.IndexOf('.') == 0 ||
            valor.IndexOf('.') == (valor.Length - 1) ||
            valor.IndexOf('@') == -1 ||
            valor.IndexOf('@') == 0 ||
            valor.IndexOf('@') == (valor.Length - 1) ||
            valor.Length <= 3 ||
            valor.Length == 0 ||
            valor.Length > 50)
        {
            throw new Exception("E-mail inválido!");
        }
        else
            email = valor;
    }

    public string GetEmail()
    {
        return email;
    }
    #endregion
}

Infraestrutura e Execução de Comandos SQL

As classes ConexaoDB e Metodos gerenciam o ciclo de vida da conexão com o banco de dados e a execução das instruções SQL.

Classe ConexaoDB

class ConexaoDB
{
    public static SqlConnection GetConexao()
    {
        string strcon = "Data Source=localhost;User ID=sa";
        SqlConnection conexao = new SqlConnection(strcon);
        conexao.Open();
        return conexao;
    }
}

Classe Metodos

class Metodos
{
    public static void ExecutaSQL(string sql)
    {
        #region EXECUTA COMANDOS NO BANCO DE DADOS
        SqlConnection conexao = ConexaoDB.GetConexao();
        try
        {
            SqlCommand comando = new SqlCommand(sql, conexao);
            comando.ExecuteNonQuery();
        }
        finally
        {
            conexao.Close();
        }
        #endregion
    }

    public static DataTable ExecutaSelect(string sql)
    {
        #region EXECUTA CONSULTAS NO BANCO DE DADOS
        SqlConnection conexao = ConexaoDB.GetConexao();
        try
        {
            SqlDataAdapter adapter = new SqlDataAdapter(sql, conexao);
            DataTable tabelaTemp = new DataTable();
            adapter.Fill(tabelaTemp);
            return tabelaTemp;
        }
        finally
        {
            conexao.Close();
        }
        #endregion
    }

    public void AlterarParaModo(modoOperacao modo)
    {
    }
}

Download

PDF Word HTML