Acceso a datos: Empezando con Dapper

195 views
Skip to first unread message

Kiquenet

unread,
Sep 15, 2017, 7:44:43 PM9/15/17
to AltNet-Hispano
Hola a todos.

Tenemos un proyecto ASP.NET WebForms, Web services, llamadas $.ajax, no muchas tablas, y llamadas a procedimientos almacenados para cada consulta.


Interesante el blog de Nick Craver, de Stackoverflow:

"Our usage of SQL is pretty simple. Simple is fast. Though some queries can be crazy, our interaction with SQL itself is fairly vanilla. We have some legacy Linq2Sql, but all new development is using Dapper, our open source Micro-ORM using POCOs. Let me put this another way: Stack Overflow has only 1 stored procedure in the database and I intend to move that last vestige into code."

Stack Overflow utiliza un high performance microORM como Dapper y sin procedimientos almacenados.


Sin duda con el acceso a datos puede haber MUCHAS opciones, pero el descubrimiento de Dapper y utilizarlo nos parece una buena acción.

Empezamos instalando Dapper y sus extensiones vía Nuget:

PM> Install-Package Dapper

 

PM> Install-Package Dapper.Contrib

 

PM> Install-Package Dapper.SqlBuilder



E impplementar una clase DAL (no son métodos estáticos, pero podría serlo) utilizando Dapper para llamar a los procedimientos SPs:


using Dapper;
 
        public DatosCurso GetCurso(int idUbicacion, string idCurso)
        {
            DatosCurso res = null;
 
            using (var connection = Utility.GetConnection())
            {
                connection.Open();
 
                var listaRes = connection.Query<DatosCurso >("APP_GetDatosCurso", new { IdUbicacion = idUbicacion, IdCurso = idCurso }, commandType: CommandType.StoredProcedure).AsList();
                if (listaRes != null && listaRes.Count > 0) res = listaRes[0];
 
                connection.Close();
            }
            return res;
 
        }

Abrimos/cerramos conexión en cada método. Podríamos pensar en utilizar una clase Helper que nos abstraiga de esos pasos con la conexión.


Dapper tamibén permite Complex Queries

Y también tiene soporte Using Async Await a partir de Net 4.5


Yendo un paso más allá de la típica clase 
helper DAL con métodos estáticos, se puede pensar en patrones como Repository y desarrollar la típica capa CRUD a partir de las clases POCOs.

El potencial de Dapper aparece con herramientas de generación de código (CodeSmith, templates T4, ....):

"
What you have is a good start to using Dapper, but I feel that Dapper isn't in it's 
own right an ORM. It is, and admits to being, a Micro-ORM. If you write your own 
POCO classes and the mappings that go with them, Dapper returns proper POCOs and 
that's all good but needs significant developer input to write the POCOs and 
maintain the mappings.

The real power of Dapper comes when you combine it with a code generation tool - 
something like CodeSmith (v2.6 was public domain, is still available, and does 
everything you need) or the now defunct MyGeneration, there are others that do the 
job just as well - Mustache springs to mind.
 

When you have codegen integrated into your build server that automatically generates 
your POCOs & mappings by interrogating your database schema, you have a *really* 
powerful tool. We've been using Dapper that way for a couple of years and it's a 
godsend. Every time we add or edit a table, view or stored proc the continuous 
builder server auto-generates the updated POCOs & mappings. Hassle-free, very fast, 
and has saved us thousands of lines of tedious ADO hand-coding. Sam Saffron, if on 
the off-chance you read this, thanks for Dapper..."


¿Algunas experiencias real-world a compartir con capa de acceso a datos con Dapper?

Saludos y gracias de antemano.






Message has been deleted

Kiquenet

unread,
Sep 16, 2017, 3:23:18 AM9/16/17
to AltNet-Hispano

Sólo unas notas más al respecto.

Podemos contemplar un SqlHelper para Dapper para facilitar las típicas operaciones CRUD

Y el siguiente paso sería empezar con generación de código:


Who wants to write basic read/insert/update/delete statements? SimpleCRUD provides simple CRUD helpers for Dapper.


En cuanto a async y Dapper unas cuestiones a tener en cuenta:

The only cautionary note is that, since it's all async, if your service or app starts getting hit too hard (this depends on your server architecture and resources), it may start returning HTTP 503 responses. So, you may need a throttler or a request queue or something. That's not something I've tackled yet, but maybe 
I'll do a future post about that.


Alguna experiencia al respecto sea capa CRUD, generadores de código para Dapper, async?
Gracias de antemano.

Reply all
Reply to author
Forward
0 new messages