Buscar contenidos

viernes, 15 de julio de 2016

Dapper ORM C# enlace tabla + entidad


Definición ( código fuente ejemplo )

...Object-Relational Mapping que se encarga de manejar el acceso a datos, la ejecución de consultas y de operaciones de inserción, actualización y borrado de datos.




public static class DBManager
    {
        private static int _Intentos = 5;

        public static DataTable Execute_QueryToDataTable(string query, string connectionString = "")
        {
            DataTable dt = new DataTable();

            int Contador = 0;
           
            while (Contador <= _Intentos)
            {
                try
                {
                    using (SqlConnection connection = new SqlConnection(connectionString))
                    {
                        using (SqlCommand command = new SqlCommand())
                        {
                            connection.Open();

                            command.Connection = connection;
                            command.CommandType = System.Data.CommandType.Text;
                            command.CommandText = query;

                            using (SqlDataReader reader = command.ExecuteReader())
                            {
                                dt.Load(reader);
                            }

                            Contador = _Intentos + 1;
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (Contador == _Intentos)
                    {
                        throw ex;
                    }

                    Contador++;
                }
            }
            return dt;

        }

        public static DataTable Execute_QueryToDataTable(string spName, Dictionary<string,string> dParameters, string connectionString = "")
        {
            DataTable dt = new DataTable();

            int Contador = 0;
           
            while (Contador <= _Intentos)
            {
                try
                {
                    using (SqlConnection connection = new SqlConnection(connectionString))
                    {
                        using (SqlCommand command = new SqlCommand())
                        {
                            connection.Open();

                            command.Connection = connection;
                            command.CommandType = System.Data.CommandType.StoredProcedure;
                            command.CommandText = spName;
                           
                            foreach (var item in dParameters)
                            {
                                command.Parameters.Add(new SqlParameter(item.Key.Trim(), item.Value.Trim()));
                            }

                            using (SqlDataReader reader = command.ExecuteReader())
                            {
                                dt.Load(reader);
                            }

                            Contador = _Intentos + 1;
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (Contador == _Intentos)
                    {
                        throw ex;
                    }

                    Contador++;
                }
            }
            return dt;

        }
      
        public static IEnumerable<T> Execute_Query<T>(string query, string connectionString = "")
        {
            IEnumerable<T> items = null;

            int Contador = 0;

            while (Contador <= _Intentos)
            {
                try
                {
                    using (SqlConnection connection = new SqlConnection(connectionString))
                    {
                        items = connection.Query<T>(query);
                    }

                    Contador = _Intentos + 1;
                }
                catch (Exception ex)
                {
                    if (Contador == _Intentos)
                    {
                        throw ex;
                    }

                    Contador++;
                }
            }
           
            return items;
        }

        public static IEnumerable<T> Execute_Query<T>(string spName, Dictionary<string, object> dParameters, string connectionString = "")
        {
            var dbArgs = new DynamicParameters();

            IEnumerable<T> items = null;

            int Contador = 0;

            while (Contador <= _Intentos)
            {
                try
                {
                    foreach (var pair in dParameters)
                    {
                        dbArgs.Add(pair.Key, pair.Value);
                    }

                    using (SqlConnection connection = new SqlConnection(connectionString))
                    {
                        return (connection.Query<T>(spName, new DynamicParameters(dbArgs), commandType: CommandType.StoredProcedure));
                    }

                    Contador = _Intentos + 1;
                }
                catch (Exception ex)
                {
                    if (Contador == _Intentos)
                    {
                        throw ex;
                    }

                    Contador++;
                }
            }

            return null;

        }

    }

public static T ConvertToEntity<T>(this DataRow tableRow) where T : new()
{
    // Create a new type of the entity I want
    Type t = typeof(T);
    T returnObject = new T();

    foreach (DataColumn col in tableRow.Table.Columns)
    {
        string colName = col.ColumnName;

        // Look for the object's property with the columns name, ignore case
        PropertyInfo pInfo = t.GetProperty(colName.ToLower(),
            BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);

        // did we find the property ?
        if (pInfo != null)
        {
            object val = tableRow[colName];

            // is this a Nullable<> type
            bool IsNullable = (Nullable.GetUnderlyingType(pInfo.PropertyType) != null);
            if (IsNullable)
            {
                if (val is System.DBNull)
                {
                    val = null;
                }
                else
                {
                    // Convert the db type into the T we have in our Nullable<T> type
                    val = Convert.ChangeType
   (val, Nullable.GetUnderlyingType(pInfo.PropertyType));
                }
            }
            else
            {
                // Convert the db type into the type of the property in our entity
                val = Convert.ChangeType(val, pInfo.PropertyType);
            }
            // Set the value of the property with the value from the db
            pInfo.SetValue(returnObject, val, null);
        }
    }

    // return the entity object with values
    return returnObject;
}

No hay comentarios:

Publicar un comentario