Skip to content

Instantly share code, notes, and snippets.

@AEROGU
Last active November 10, 2019 08:20
Show Gist options
  • Save AEROGU/23abb3039c4a2e117a30231af3525fc0 to your computer and use it in GitHub Desktop.
Save AEROGU/23abb3039c4a2e117a30231af3525fc0 to your computer and use it in GitHub Desktop.
Ejemplo muy simple de uso de paquete NuGet "Dapper" para mapear automáticamente resultado de una consulta en un objeto en C# VS2019.
using Dapper;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Security.Permissions;
using System.Text;
using System.Threading.Tasks;
namespace EjemploDapper
{
/// <summary>
/// Ejemplo básico para mapeo en usando Dapper.
/// </summary>
/// <remarks>
/// Llamar get_user_data usando los métodos entre try...catch por si hay errorers de conexión mostrar el mensaje.
/// O implementar algún Error_handler como el de EiffelStudio.
/// Es una buena práctica separar en una carpeta los objetos y en otra los comandos que los cargan.
/// </remarks>
/// <seealso cref="https://www.infoworld.com/article/3025784/how-to-use-the-dapper-orm-in-c.html"/>
public class EjemploDapper
{
public List<User> get_user_data(string a_username, string a_password)
{
using (IDbConnection db = new MySqlConnection(Properties.Settings.Default.connection_string))
{
return (List<User>)db.Query<User>
($"select person_id, username, status from users where username='{a_username}' and password=sha('{a_password}');");
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EjemploDapper
{
/// <summary>
/// Clase para mapear una consulta con Dapper
/// Se creará una lista de objetos de esta clase.
/// </summary>
public class User
{
public int person_id { get; set; }
public string username { get; set; }
public string status { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment