SlideShare a Scribd company logo
The micro-ORM that will
change your life
Davide Mauri, Director of Software Engineering,
Sensoria
Dapper .NET
Please silence
cell phones
Please silence
cell phones
2
Free online webinar
events
Free 1-day local
training events
Local user groups
around the world
Online special
interest user groups
Business analytics
training
Free Online Resources
PASS Blog
White Papers
Session Recordings
Newsletter www.pass.org
Explore everything PASS has to offer
PASS Connector
BA Insights
Get involved
Davide Mauri
Director of Software
Engineering, Sensoria
A DEVELOPER
20 years in development, started with C++,
then VB & Delphi, then C# and now also
Python. Active on GitHub
A DATABASE GUY
15 years spent on High-Performance
Database, Data Warehouse, Business
Intelligence and Business Analytics projects.
Data Platform MVP since 2007
AGILE & AUTOMATION FAN
Fan of Agile Methodology and Automation, I
try to apply them everywhere he can, to
make sure that "people think, machines do".
IoT is where I live and work now, making
sure the above two worlds work well
together
/davidemauri @mauridb
http://www.sensoriafitness.com/
Agenda
• The story so far: DEV, DBA, ORM, MicroORM
• Dapper.NET
• Basic Usage
• Advanced Stuff
• Extensions
• Conclusions
Let’s start with a definition
fric·tion
The resistance that data finds when it moves from the application to the
database or vice-versa
The resistance that one surface or object encounters when moving over
another.
Friction is bad
- It will slow your performance down
- It will make your DBA scream
- It will make your DEV scream
- It will increase solution costs
© http://becauseracecar.net
Impedance Mismatch
Friction exists because of the “Impedance Mismatch”
• Object Oriented Models and Relational Models are different
• Yet they have to co-exists since they are both really good at their job
Friction also gets generated between teams (DBA vs DEV)
• Code First or Database First?
• Stored Procedure or SQL generated on the fly?
What’s your current status?
Beginner Advanced
I really encourage you to share this presentation with your developers.
The story so far…
DEV usually don’t like to write (and in general deal with) databases, and
SQL code especially
• It looks old…wait: it IS old!
• It’s not OO
• It’s complex/strange/illogic
• It’s really not part of my job
So let’s have something to write the SQL code for us so we can just abstract
from it
• It will even make application work with any DB! That’s a strong selling
point to give to my boss!
The story so far…
ORM (Object-Relational-Mapping) to the rescue
• DEVs don’t write the code
• DBAs still can’t put their hands in code but now is the ORM to blame
Everyone is happy from a relationship perspective
The story so far…
Performance still crappy. Really crappy. Let’s move to a NoSQL db then.
• It was cool in that presentation right?
• No more normalization stuff….Ehy is the word “Normalization” that one
I’m seeing in MongoDB docs?
• Nice: no joins! Well uhm…but now we have *a lot* of duplication in our
data.
• But the fact that I can just put and get my class is soooooo cool and
comfortable.
• The DBA will figure out later how the extract data from it and if the data has some logical
meaning or not. Even in which property the data is stored. Damn! Someone created the
InvoiceValue property but we already had the InvoceAmout to be used. Oh well, let’s add an if,
no, better!, let’s create a solution that via IoC that allows us to configure where I have to look
for Invoice amount. Great let’s do that for all the other fields too!
The story so far…
ORM like EF or NHibernate wrote the SQL code on the fly
• No why to change it if at some point you discover it could have been
written so much better
It would be nice if one could just behave like if the SQL code doesn’t exists:
the DBA will write the code for me and I just map it to my OO objects
• Which is boring anyway.
• There is a tool that, given a query in can automatically map the result
into an OO object of mine?
The story so far…
Devs recently come to realize that – an average - they need to use a DB to
excel in their job
• DB is quite cool again. Lock-Free tables, columnar storage, cool uh?
Still writing interacting with the db is boring (which means error prone)
• Create the connection
• Execute the query
• Map the query to OO objects
• Close the connection
• Oh wait, yeah, exception management
The story so far…
DBA they want to be able to Improve, Fix, Cleanup, Tweak SQL code
written by DEVs.
• Because if the db is slow it’s THEIR problem, even if they DIDN’T wrote
that code.
• But actually they don’t really want to touch DEVs code….is so dirty! And
it’s barely comprehensible. And look how he wrote this statement, oh my
gosh, this prevents index to be used, geez! Look: my poor server is just
out of CPU and I/O!
• Phone calls. It’s the customer care complaining that they cannot do their job,
everything is slow
What a MicroORM is?
Just do one simple thing, take data coming from a database query an use it
to populate pre-existing or dynamic objects
• Nothing more and nothing less
• No frills approach: Not identity mapping, no lazy load
• SQL *MUST* be written manually (no LINQ or other intermediate
language like HQL)
• Tries not to introduce friction when accessing and operating on data
One of the most used, proven and well-known is Dapper .NET
https://blogs.msdn.microsoft.com/dotnet/2016/11/09/net-core-data-access/
Why MicroORM?
You are interested in:
GET GREAT PERFORMANCE
REDUCE RESOURCE COSTS
BE IN CONTROL
Dapper .NET
First public release on Apr, 2011
Supports .NET “Classic” and .NET Core
Supports any RDBMS supported by .NET ADO providers: SQL Server, SQL
Lite, PostgreSQL, Oracle, MySQL, Firebird, …
Works as an extensions to IDBConnection interface
Installation via NuGet or dotnet add package
Dapper .NET
High performance Micro-ORM:
• YOU Create POCO classes
• YOU Write SQL
Map SQL results to POCO classes
• Automatically done 
Very Fast!
Where does performances come from?
DynamicMethod
• Inject MSIL directly in the body
of existing code
• Somehow like the “asm” keyword of C/C++
Allows mapping to POCO properties
without Reflection
• Almost no performance impact
• No more boring GetInt32()/GetString()/Get…() code 
Dapper .NET
Full source code available on GitHub
https://github.com/StackExchange/dapper-dot-net
Created and used by Stack Exchange
• Battle Tested! 
• Born here: How I learned to stop worrying and write my own ORM
Support available on GitHub and Stack Overflow:
http://stackoverflow.com/questions/tagged/dapper
The Basics
Dapper .NET
Dapper .NET
Extends the IDBConnection interface
Provides three main methods
• Query
• Execute
• ExecuteScalar
Dapper .NET
The three main methods are implemented in various ways
• To support Async/Await
• To support Single/First/FirstOrDefault
• To support multiple results set
• To support DataReaders
Results can be mapped to
• (Enumerable of) POCO classes
• (Enumerable of) dynamic objects
Parametric Queries
All methods support parametric queries.
Parameters are identified using the “@” symbol:
Parameters can be
• Anonymous Objects
• DynamicParameters Objects
• List (to support then IN clause)
SELECT [Id], [FirstName], [LastName]
FROM dbo.[Users] WHERE Id = @Id
Stored Procedures
Stored procedures can be executed easily
• Set CommandType to StoredProcedure
• Do not specify EXEC[UTE]
• Pass the parameters as shown before
• Return value and Output Parameters can be obtained via
DynamicParameters
• Result can be mapped to (Enumerable of) POCOs or Dynamic Objects just as an
ad-hoc query
The Basics
Demo
Advanced
Features
Dapper .NET
Multiple Execution
Use a IEnumerable parameter to execute the statement for each item.
• Only “Execute” Method supports this feature
var paramList = new List<DynamicParameters>();
paramList.Add(p1)
paramList.Add(p2)
paramList.Add(p3)
var affectedRows = conn.Execute(“<SQL>”, paramList)
Multiple Results
Mapping multiple result set to different object is also supported
“Read” is just like the “Query” method and supports all overloads and
specialized methods (eg: ReadFirst, ReadSingle, AsyncRead…)
using (var qm = conn.QueryMultiple(“SELECT…;SELECT…”))
{
var users = qm.Read<User>();
var companies = qm.Read<Company>();
}
Multiple Mapping
It’s also possible to take data from one row and split it in multiple objects
Table-Valued Parameters
Any IEnumerable or DataTable can be used. (As expected)
Use the extension method .AsTableValuedParameter
Special SQL Server Data Types
All ”special” SQL Server Data Types are supported:
• Geometry
• Geography
• HierarchyID
Just use them as usual
• Reference and Use Microsoft.SqlServer.Types
• Use them with Dapper as any other object
JSON
JSON in SQL Server is “just” text
Dapper deals with it as such, so Serialization and Deserialization must be
done manually
Customizing Interaction with database
There are two way to customize how Dapper will map data to and from
database:
• Mapping: Which property is mapped to column and vice-versa
• Handling: How property’s value is loaded into to database column and
vice-versa
Custom Data Mapping
It is possible to replace default “same name” convention mappings
Define mapping between model and database by creating a
CustomPropertyTypeMap
Make it active via SqlMapper.SetTypeMap
Custom Type Handling
Explicitly states how handling data between model and database should
happen
• Opens up a world of possibilities, to handle even the most complex
scenarios
SqlMapper is the object that behind the scenes does the mapping
• Can be used explicitly: SqlMapper.AddTypeHandler(<TypeHandler>)
Create your own type handler
• Create a class that derives from SqlMapper.TypeHandler
• Implement methods Parse and SetValue
Transactions
Transaction are supported via the usual:
• BeginTransaction
• TransactionScope
Buffered & Unbuffered results
By default the entire result set will be loaded in memory and then returned
to you
• The aim is to stay connected to the database for the smallest amount of
time possible
• Of course this means memory usage
In order to have the results usable as soon as they are streamed from the
database the “unbuffered” option exists
conn.Query("SELECT …;", buffered: false);
Advanced
Features
Demo
Extensions
Dapper .NET
Well-Known Extensions
A Growing Ecosystem! Extend Dapper features. Two main families:
• mainly adding CRUD support (by generating SQL on-the-fly)
• customize mapping db to class
A complete list is here:
• http://dapper-tutorial.net/dapper-contrib-third-party-library
ORM and micro-ORM
Now the question is: Is a MicroORM good for me?
If you need performance, know SQL and want/need to be in control of
everything: MicroORM is the way to go
• And, btw, for me, a (Backend) Developer *must* know SQL!
If you prefer more support with compile-time, object tracking, intellisense,
etc. and don’t want/need to write your own SQL: ORM is ok
A mix of the two is also possible if needed.
Conclusions & Alternatives
Other MicroORM you may want to take a look at
• ORMLite
• PetaPoco
• Massive
• Simple.Data
Session evaluations
Download the GuideBook App
and search: PASS Summit 2017
Follow the QR code link
displayed on session signage
throughout the conference
venue and in the program guide
Your feedback is important and valuable.
Go to passSummit.com
Submit by 5pm Friday, November 10th to win prizes. 3 Ways to Access:
Thank You
Learn more from Speaker Name
info@davidemauri.it@mauridb

More Related Content

Similar to Dapper: the microORM that will change your life (20)

PDF
How To Do Excel-Like Row Selection in jQuery DataTable?
Polyxer Systems
 
PDF
Entity Framework Interview Questions PDF By ScholarHat
Scholarhat
 
PPTX
Orms vs Micro-ORMs
David Paquette
 
PPTX
refORM: Death to ORMs in .NET
James Hughes
 
PDF
Object Relational Mapping with Dapper (Micro ORM)
Muhammad Umar
 
PPTX
Entity Framework v1 and v2
Eric Nelson
 
PPTX
Domain oriented development
rajmundr
 
PPTX
Entity Framework V1 and V2
ukdpe
 
PPT
What's New for Data?
ukdpe
 
PPT
Orms
jananb
 
PPT
Orms
Sai Kiran
 
PPT
L2s 090701234157 Phpapp02
google
 
PPTX
.NET Database Toolkit
wlscaudill
 
PPTX
Introduction to Telerik OpenAccess ORM
peterbahaa
 
PDF
Learn Entity Framework in a day with Code First, Model First and Database First
Jibran Rasheed Khan
 
PPTX
Advanced .NET Data Access with Dapper
David Paquette
 
PPT
Orm and hibernate
s4al_com
 
PPTX
Micro ORM vs Entity Framework
Axilis
 
PPTX
What Impact Will Entity Framework Have On Architecture
Eric Nelson
 
PPTX
ORMs Meet SQL
Ricardo Peres
 
How To Do Excel-Like Row Selection in jQuery DataTable?
Polyxer Systems
 
Entity Framework Interview Questions PDF By ScholarHat
Scholarhat
 
Orms vs Micro-ORMs
David Paquette
 
refORM: Death to ORMs in .NET
James Hughes
 
Object Relational Mapping with Dapper (Micro ORM)
Muhammad Umar
 
Entity Framework v1 and v2
Eric Nelson
 
Domain oriented development
rajmundr
 
Entity Framework V1 and V2
ukdpe
 
What's New for Data?
ukdpe
 
Orms
jananb
 
Orms
Sai Kiran
 
L2s 090701234157 Phpapp02
google
 
.NET Database Toolkit
wlscaudill
 
Introduction to Telerik OpenAccess ORM
peterbahaa
 
Learn Entity Framework in a day with Code First, Model First and Database First
Jibran Rasheed Khan
 
Advanced .NET Data Access with Dapper
David Paquette
 
Orm and hibernate
s4al_com
 
Micro ORM vs Entity Framework
Axilis
 
What Impact Will Entity Framework Have On Architecture
Eric Nelson
 
ORMs Meet SQL
Ricardo Peres
 

More from Davide Mauri (20)

PPTX
Azure serverless Full-Stack kickstart
Davide Mauri
 
PPTX
Agile Data Warehousing
Davide Mauri
 
PPTX
When indexes are not enough
Davide Mauri
 
PPTX
Building a Real-Time IoT monitoring application with Azure
Davide Mauri
 
PPTX
SSIS Monitoring Deep Dive
Davide Mauri
 
PPTX
Azure SQL & SQL Server 2016 JSON
Davide Mauri
 
PPTX
SQL Server & SQL Azure Temporal Tables - V2
Davide Mauri
 
PPTX
SQL Server 2016 Temporal Tables
Davide Mauri
 
PPTX
SQL Server 2016 What's New For Developers
Davide Mauri
 
PPTX
Azure Stream Analytics
Davide Mauri
 
PPTX
Azure Machine Learning
Davide Mauri
 
PPTX
Dashboarding with Microsoft: Datazen & Power BI
Davide Mauri
 
PPTX
Azure ML: from basic to integration with custom applications
Davide Mauri
 
PPTX
Event Hub & Azure Stream Analytics
Davide Mauri
 
PPTX
SQL Server 2016 JSON
Davide Mauri
 
PPTX
SSIS Monitoring Deep Dive
Davide Mauri
 
PPTX
Real Time Power BI
Davide Mauri
 
PPTX
AzureML - Creating and Using Machine Learning Solutions (Italian)
Davide Mauri
 
PPTX
Datarace: IoT e Big Data (Italian)
Davide Mauri
 
PPTX
Azure Machine Learning (Italian)
Davide Mauri
 
Azure serverless Full-Stack kickstart
Davide Mauri
 
Agile Data Warehousing
Davide Mauri
 
When indexes are not enough
Davide Mauri
 
Building a Real-Time IoT monitoring application with Azure
Davide Mauri
 
SSIS Monitoring Deep Dive
Davide Mauri
 
Azure SQL & SQL Server 2016 JSON
Davide Mauri
 
SQL Server & SQL Azure Temporal Tables - V2
Davide Mauri
 
SQL Server 2016 Temporal Tables
Davide Mauri
 
SQL Server 2016 What's New For Developers
Davide Mauri
 
Azure Stream Analytics
Davide Mauri
 
Azure Machine Learning
Davide Mauri
 
Dashboarding with Microsoft: Datazen & Power BI
Davide Mauri
 
Azure ML: from basic to integration with custom applications
Davide Mauri
 
Event Hub & Azure Stream Analytics
Davide Mauri
 
SQL Server 2016 JSON
Davide Mauri
 
SSIS Monitoring Deep Dive
Davide Mauri
 
Real Time Power BI
Davide Mauri
 
AzureML - Creating and Using Machine Learning Solutions (Italian)
Davide Mauri
 
Datarace: IoT e Big Data (Italian)
Davide Mauri
 
Azure Machine Learning (Italian)
Davide Mauri
 
Ad

Recently uploaded (20)

PPTX
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
PDF
Top Agile Project Management Tools for Teams in 2025
Orangescrum
 
PPTX
Home Care Tools: Benefits, features and more
Third Rock Techkno
 
PDF
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
PDF
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
PDF
MiniTool Power Data Recovery 8.8 With Crack New Latest 2025
bashirkhan333g
 
PPTX
Coefficient of Variance in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
Driver Easy Pro 6.1.1 Crack Licensce key 2025 FREE
utfefguu
 
PPTX
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
PPTX
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
PPTX
Comprehensive Risk Assessment Module for Smarter Risk Management
EHA Soft Solutions
 
PDF
4K Video Downloader Plus Pro Crack for MacOS New Download 2025
bashirkhan333g
 
PPTX
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PPTX
Homogeneity of Variance Test Options IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PPTX
Hardware(Central Processing Unit ) CU and ALU
RizwanaKalsoom2
 
PDF
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih Küçük
 
PPTX
Finding Your License Details in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
NEW-Viral>Wondershare Filmora 14.5.18.12900 Crack Free
sherryg1122g
 
PDF
How to Hire AI Developers_ Step-by-Step Guide in 2025.pdf
DianApps Technologies
 
PDF
Wondershare PDFelement Pro Crack for MacOS New Version Latest 2025
bashirkhan333g
 
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
Top Agile Project Management Tools for Teams in 2025
Orangescrum
 
Home Care Tools: Benefits, features and more
Third Rock Techkno
 
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
MiniTool Power Data Recovery 8.8 With Crack New Latest 2025
bashirkhan333g
 
Coefficient of Variance in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Driver Easy Pro 6.1.1 Crack Licensce key 2025 FREE
utfefguu
 
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
Comprehensive Risk Assessment Module for Smarter Risk Management
EHA Soft Solutions
 
4K Video Downloader Plus Pro Crack for MacOS New Download 2025
bashirkhan333g
 
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Homogeneity of Variance Test Options IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Hardware(Central Processing Unit ) CU and ALU
RizwanaKalsoom2
 
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih Küçük
 
Finding Your License Details in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
NEW-Viral>Wondershare Filmora 14.5.18.12900 Crack Free
sherryg1122g
 
How to Hire AI Developers_ Step-by-Step Guide in 2025.pdf
DianApps Technologies
 
Wondershare PDFelement Pro Crack for MacOS New Version Latest 2025
bashirkhan333g
 
Ad

Dapper: the microORM that will change your life

  • 1. The micro-ORM that will change your life Davide Mauri, Director of Software Engineering, Sensoria Dapper .NET
  • 2. Please silence cell phones Please silence cell phones 2
  • 3. Free online webinar events Free 1-day local training events Local user groups around the world Online special interest user groups Business analytics training Free Online Resources PASS Blog White Papers Session Recordings Newsletter www.pass.org Explore everything PASS has to offer PASS Connector BA Insights Get involved
  • 4. Davide Mauri Director of Software Engineering, Sensoria A DEVELOPER 20 years in development, started with C++, then VB & Delphi, then C# and now also Python. Active on GitHub A DATABASE GUY 15 years spent on High-Performance Database, Data Warehouse, Business Intelligence and Business Analytics projects. Data Platform MVP since 2007 AGILE & AUTOMATION FAN Fan of Agile Methodology and Automation, I try to apply them everywhere he can, to make sure that "people think, machines do". IoT is where I live and work now, making sure the above two worlds work well together /davidemauri @mauridb http://www.sensoriafitness.com/
  • 5. Agenda • The story so far: DEV, DBA, ORM, MicroORM • Dapper.NET • Basic Usage • Advanced Stuff • Extensions • Conclusions
  • 6. Let’s start with a definition fric·tion The resistance that data finds when it moves from the application to the database or vice-versa The resistance that one surface or object encounters when moving over another. Friction is bad - It will slow your performance down - It will make your DBA scream - It will make your DEV scream - It will increase solution costs © http://becauseracecar.net
  • 7. Impedance Mismatch Friction exists because of the “Impedance Mismatch” • Object Oriented Models and Relational Models are different • Yet they have to co-exists since they are both really good at their job Friction also gets generated between teams (DBA vs DEV) • Code First or Database First? • Stored Procedure or SQL generated on the fly?
  • 8. What’s your current status? Beginner Advanced I really encourage you to share this presentation with your developers.
  • 9. The story so far… DEV usually don’t like to write (and in general deal with) databases, and SQL code especially • It looks old…wait: it IS old! • It’s not OO • It’s complex/strange/illogic • It’s really not part of my job So let’s have something to write the SQL code for us so we can just abstract from it • It will even make application work with any DB! That’s a strong selling point to give to my boss!
  • 10. The story so far… ORM (Object-Relational-Mapping) to the rescue • DEVs don’t write the code • DBAs still can’t put their hands in code but now is the ORM to blame Everyone is happy from a relationship perspective
  • 11. The story so far… Performance still crappy. Really crappy. Let’s move to a NoSQL db then. • It was cool in that presentation right? • No more normalization stuff….Ehy is the word “Normalization” that one I’m seeing in MongoDB docs? • Nice: no joins! Well uhm…but now we have *a lot* of duplication in our data. • But the fact that I can just put and get my class is soooooo cool and comfortable. • The DBA will figure out later how the extract data from it and if the data has some logical meaning or not. Even in which property the data is stored. Damn! Someone created the InvoiceValue property but we already had the InvoceAmout to be used. Oh well, let’s add an if, no, better!, let’s create a solution that via IoC that allows us to configure where I have to look for Invoice amount. Great let’s do that for all the other fields too!
  • 12. The story so far… ORM like EF or NHibernate wrote the SQL code on the fly • No why to change it if at some point you discover it could have been written so much better It would be nice if one could just behave like if the SQL code doesn’t exists: the DBA will write the code for me and I just map it to my OO objects • Which is boring anyway. • There is a tool that, given a query in can automatically map the result into an OO object of mine?
  • 13. The story so far… Devs recently come to realize that – an average - they need to use a DB to excel in their job • DB is quite cool again. Lock-Free tables, columnar storage, cool uh? Still writing interacting with the db is boring (which means error prone) • Create the connection • Execute the query • Map the query to OO objects • Close the connection • Oh wait, yeah, exception management
  • 14. The story so far… DBA they want to be able to Improve, Fix, Cleanup, Tweak SQL code written by DEVs. • Because if the db is slow it’s THEIR problem, even if they DIDN’T wrote that code. • But actually they don’t really want to touch DEVs code….is so dirty! And it’s barely comprehensible. And look how he wrote this statement, oh my gosh, this prevents index to be used, geez! Look: my poor server is just out of CPU and I/O! • Phone calls. It’s the customer care complaining that they cannot do their job, everything is slow
  • 15. What a MicroORM is? Just do one simple thing, take data coming from a database query an use it to populate pre-existing or dynamic objects • Nothing more and nothing less • No frills approach: Not identity mapping, no lazy load • SQL *MUST* be written manually (no LINQ or other intermediate language like HQL) • Tries not to introduce friction when accessing and operating on data One of the most used, proven and well-known is Dapper .NET https://blogs.msdn.microsoft.com/dotnet/2016/11/09/net-core-data-access/
  • 16. Why MicroORM? You are interested in: GET GREAT PERFORMANCE REDUCE RESOURCE COSTS BE IN CONTROL
  • 17. Dapper .NET First public release on Apr, 2011 Supports .NET “Classic” and .NET Core Supports any RDBMS supported by .NET ADO providers: SQL Server, SQL Lite, PostgreSQL, Oracle, MySQL, Firebird, … Works as an extensions to IDBConnection interface Installation via NuGet or dotnet add package
  • 18. Dapper .NET High performance Micro-ORM: • YOU Create POCO classes • YOU Write SQL Map SQL results to POCO classes • Automatically done  Very Fast!
  • 19. Where does performances come from? DynamicMethod • Inject MSIL directly in the body of existing code • Somehow like the “asm” keyword of C/C++ Allows mapping to POCO properties without Reflection • Almost no performance impact • No more boring GetInt32()/GetString()/Get…() code 
  • 20. Dapper .NET Full source code available on GitHub https://github.com/StackExchange/dapper-dot-net Created and used by Stack Exchange • Battle Tested!  • Born here: How I learned to stop worrying and write my own ORM Support available on GitHub and Stack Overflow: http://stackoverflow.com/questions/tagged/dapper
  • 22. Dapper .NET Extends the IDBConnection interface Provides three main methods • Query • Execute • ExecuteScalar
  • 23. Dapper .NET The three main methods are implemented in various ways • To support Async/Await • To support Single/First/FirstOrDefault • To support multiple results set • To support DataReaders Results can be mapped to • (Enumerable of) POCO classes • (Enumerable of) dynamic objects
  • 24. Parametric Queries All methods support parametric queries. Parameters are identified using the “@” symbol: Parameters can be • Anonymous Objects • DynamicParameters Objects • List (to support then IN clause) SELECT [Id], [FirstName], [LastName] FROM dbo.[Users] WHERE Id = @Id
  • 25. Stored Procedures Stored procedures can be executed easily • Set CommandType to StoredProcedure • Do not specify EXEC[UTE] • Pass the parameters as shown before • Return value and Output Parameters can be obtained via DynamicParameters • Result can be mapped to (Enumerable of) POCOs or Dynamic Objects just as an ad-hoc query
  • 28. Multiple Execution Use a IEnumerable parameter to execute the statement for each item. • Only “Execute” Method supports this feature var paramList = new List<DynamicParameters>(); paramList.Add(p1) paramList.Add(p2) paramList.Add(p3) var affectedRows = conn.Execute(“<SQL>”, paramList)
  • 29. Multiple Results Mapping multiple result set to different object is also supported “Read” is just like the “Query” method and supports all overloads and specialized methods (eg: ReadFirst, ReadSingle, AsyncRead…) using (var qm = conn.QueryMultiple(“SELECT…;SELECT…”)) { var users = qm.Read<User>(); var companies = qm.Read<Company>(); }
  • 30. Multiple Mapping It’s also possible to take data from one row and split it in multiple objects
  • 31. Table-Valued Parameters Any IEnumerable or DataTable can be used. (As expected) Use the extension method .AsTableValuedParameter
  • 32. Special SQL Server Data Types All ”special” SQL Server Data Types are supported: • Geometry • Geography • HierarchyID Just use them as usual • Reference and Use Microsoft.SqlServer.Types • Use them with Dapper as any other object
  • 33. JSON JSON in SQL Server is “just” text Dapper deals with it as such, so Serialization and Deserialization must be done manually
  • 34. Customizing Interaction with database There are two way to customize how Dapper will map data to and from database: • Mapping: Which property is mapped to column and vice-versa • Handling: How property’s value is loaded into to database column and vice-versa
  • 35. Custom Data Mapping It is possible to replace default “same name” convention mappings Define mapping between model and database by creating a CustomPropertyTypeMap Make it active via SqlMapper.SetTypeMap
  • 36. Custom Type Handling Explicitly states how handling data between model and database should happen • Opens up a world of possibilities, to handle even the most complex scenarios SqlMapper is the object that behind the scenes does the mapping • Can be used explicitly: SqlMapper.AddTypeHandler(<TypeHandler>) Create your own type handler • Create a class that derives from SqlMapper.TypeHandler • Implement methods Parse and SetValue
  • 37. Transactions Transaction are supported via the usual: • BeginTransaction • TransactionScope
  • 38. Buffered & Unbuffered results By default the entire result set will be loaded in memory and then returned to you • The aim is to stay connected to the database for the smallest amount of time possible • Of course this means memory usage In order to have the results usable as soon as they are streamed from the database the “unbuffered” option exists conn.Query("SELECT …;", buffered: false);
  • 41. Well-Known Extensions A Growing Ecosystem! Extend Dapper features. Two main families: • mainly adding CRUD support (by generating SQL on-the-fly) • customize mapping db to class A complete list is here: • http://dapper-tutorial.net/dapper-contrib-third-party-library
  • 42. ORM and micro-ORM Now the question is: Is a MicroORM good for me? If you need performance, know SQL and want/need to be in control of everything: MicroORM is the way to go • And, btw, for me, a (Backend) Developer *must* know SQL! If you prefer more support with compile-time, object tracking, intellisense, etc. and don’t want/need to write your own SQL: ORM is ok A mix of the two is also possible if needed.
  • 43. Conclusions & Alternatives Other MicroORM you may want to take a look at • ORMLite • PetaPoco • Massive • Simple.Data
  • 44. Session evaluations Download the GuideBook App and search: PASS Summit 2017 Follow the QR code link displayed on session signage throughout the conference venue and in the program guide Your feedback is important and valuable. Go to passSummit.com Submit by 5pm Friday, November 10th to win prizes. 3 Ways to Access:
  • 45. Thank You Learn more from Speaker Name [email protected]@mauridb