Created
February 6, 2011 17:13
-
-
Save marcioalthmann/813519 to your computer and use it in GitHub Desktop.
Classe de acesso a dados, onde não existia EF e eu não usava NHibernate.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Configuration; | |
using System.Data.SqlClient; | |
using System.Data; | |
using System.IO; | |
using System.Reflection; | |
using System.Web; | |
namespace Dados | |
{ | |
public class DadosBase | |
{ | |
public void ExecutarComando(string sql, Dictionary<string, object> parametros) | |
{ | |
using (var conexao = new SqlConnection("stringDeConexao")) | |
{ | |
using (var comando = new SqlCommand()) | |
{ | |
comando.Connection = conexao; | |
comando.CommandText = sql; | |
if (parametros != null) | |
{ | |
foreach (var parametro in parametros) | |
{ | |
var novoParametro = new SqlParameter { Value = parametro.Value, ParameterName = parametro.Key}; | |
comando.Parameters.Add(novoParametro); | |
} | |
} | |
try | |
{ | |
conexao.Open(); | |
comando.ExecuteNonQuery(); | |
} | |
catch (SqlException exception) | |
{ | |
// Salva log | |
} | |
} | |
} | |
} | |
public IList<T> ExecutarSelect<T>(string sql, string[] propriedades, Dictionary<string, object> parametros) where T : class, new() | |
{ | |
var lista = new List<T>(); | |
using (var conexao = new SqlConnection("stringDeConexao")) | |
{ | |
using (var comando = new SqlCommand()) | |
{ | |
comando.Connection = conexao; | |
comando.CommandText = sql; | |
if (parametros != null) | |
{ | |
foreach (KeyValuePair<string, object> parametro in parametros) | |
{ | |
comando.Parameters.Add(new SqlParameter(parametro.Key, parametro.Value)); | |
} | |
} | |
try | |
{ | |
conexao.Open(); | |
using (var dataReader = comando.ExecuteReader()) | |
{ | |
string FieldName = String.Empty; | |
if (dataReader != null) | |
{ | |
if (dataReader.HasRows) | |
{ | |
while (dataReader.Read()) | |
{ | |
T objeto = new T(); | |
for (var i = 0; i < dataReader.FieldCount; i++) | |
{ | |
FieldName = dataReader.GetName(i); | |
if (dataReader[FieldName].ToString() == "") | |
{ | |
continue; | |
} | |
if (objeto.GetType().GetProperty(FieldName).PropertyType.Name.Equals("Boolean")) | |
{ | |
objeto.GetType().GetProperty(FieldName).SetValue(objeto,dataReader[FieldName],null); | |
} | |
else | |
{ | |
objeto.GetType().GetProperty(FieldName).SetValue(objeto,dataReader[FieldName],null); | |
} | |
} | |
lista.Add(objeto); | |
} | |
} | |
} | |
} | |
} | |
catch (SqlException exception) | |
{ | |
// Salva log | |
} | |
} | |
} | |
return lista; | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment