SlideShare a Scribd company logo
Advanced Data Access
with Dapper
@Dave_Paquette
Microsoft MVP (ASP.NET/IIS)
contactme@davepaquette.com
http://www.davepaquette.com
Data Access
How did we get here?
Why is this so hard?
public class Foo
{
//…some properties
}
SQL Server
Data Access in .NET
• In the beginning there was System.Data
• IDbConnection
• IDbCommand
• IDataReader
• IDbTransaction
Sytem.Data - Reading Records
var results = new List<Employee>();
using (SqlConnection connection = new SqlConnection(Settings.ConnectionString))
{
SqlCommand command = new SqlCommand(“SELECT * FROM Employees”, connection);
connection.Open();
IDataReader reader = command.ExecuteReader();
while (reader.Read())
{
results.Add(ReadSingleRow(reader));
}
reader.Close();
}
return results;
The ORMs will save us
• Hide details of database
• Generate SQL based on object model and configuration
• ChangeTracking
• Complex mapping strategies
• Many-to-many relationships
• Inheritance
Popular ORMs
•Entity Framework
•nHibernate?
•Linq2Sql?
ORM Pain Points
• Black box code generation –What is going on?
• Performance Problems
• Eager Loading vs Lazy Loading
• Complex Inheritance Chains
• Dealing with disconnected entities (in a web context)
The Micro-ORMs will save us!
• Query --> Objects
• Usually focused on speed
• Light on features
Popular Micro-ORMs
• Dapper
• PetaPOCO
• Massive
• Simple.Data
Dapper
• Used in production at Stack Exchange
• Super fast and easy to use
Performance of SELECT mapping over 500
iterations - POCO serialization
Method Duration
Hand coded (using a SqlDataReader) 47ms
Dapper ExecuteMapperQuery 49ms
ServiceStack.OrmLite (QueryById) 50ms
PetaPoco 52ms
BLToolkit 80ms
SubSonic CodingHorror 107ms
NHibernate SQL 104ms
Linq 2 SQL ExecuteQuery 181ms
Entity framework ExecuteStoreQuery 631ms
https://github.com/StackExchange/dapper-dot-net#performance-of-select-mapping-over-500-iterations---dynamic-serialization
How can it be that fast?
• Dapper dynamically writes code for you
• Emits IL code for tasks like loading a data
reader into an object
• https://github.com/StackExchange/Dapper/blo
b/master/Dapper/SqlMapper.cs#L3078
Dapper works on Database Connections
A set of extension methods on IDbConnection
Aircraft aircraft;
using (var connection = new SqlConnection(_connectionString))
{
await connection.OpenAsync(); //Optional
var query = "SELECT * FROM Aircraft WHERE Id = @Id";
Aircraft aircraft = await connection.QuerySingleAsync<Aircraft>(query, new {Id = id});
}
Querying Simple Objects
Aircraft aircraft = await connection.QuerySingleAsync<Aircraft>(query, new {Id = id});
IEnumerable<Aircraft> aircraft = await connection.QueryAsync<Aircraft>(query);
Loading Related Objects – Multi-Mapping
• Write a single query that returns all the data in a single row
scheduledFlights =
await connection.QueryAsync<ScheduledFlight, Airport, ScheduledFlight>(query,
(flight, airport) => {
flight.Airport = airport;
return flight;
},
new{FromCode = from} );
Multi-Mapping Caveats
• Data duplication
• Query returns a bloated data set
• Multiple instances of an object that represent the same thing
• This is totally fine forOne-to-One relationships
• No duplication here
Loading Related Objects – Multiple Queries
• Get data using multiple queries and wire them up yourself
• Still executed in a single command that returns multiple results sets
using (var multi = await connection.QueryMultipleAsync(query, new{FromCode = from} ))
{
scheduledFlights = multi.Read<ScheduledFlight>();
var airports = multi.Read<Airport>().ToDictionary(a => a.Id);
foreach(var flight in scheduledFlights)
{
flight.Airport = airports[flight.AirportId];
}
}
Multi-Mapping vs Multiple Queries
100 ScheduledFlight Records 1,000 ScheduledFlight Records
Method Mean
MultiMapping 926.5 us
MultipleResultSets 705.9 us
Method Mean
MultiMapping 5.098 ms
MultipleResultSets 2.809 ms
Loading More Complex Object Graphs
Loading More Complex Object Graphs
Paging through large collections
• Use an OFFSET FETCH query
• Include a total count in the result
SELECT * FROM Flight f
INNER JOIN ScheduledFlight sf
ON f.ScheduledFlightId = sf.Id
ORDER BY Day, FlightNumber
OFFSET 0 ROWS
FETCH NEXT 10 ROWS ONLY
SELECT COUNT(*) FROM Flight f
INNER JOIN ScheduledFlight sf
ON f.ScheduledFlightId = sf.Id
Insert / Update / Delete
• Use the ExecuteAsync method
• Built-in support for batch inserts
await connection.ExecuteAsync(
@"INSERT INTO Flight(ScheduledFlightId, Day, ScheduledDeparture,
ScheduledArrival)
VALUES(@ScheduledFlightId, @Day, @ScheduledDeparture, @ScheduledArrival)",
flights);
Buffering
•Working with really large result sets?
• Consider setting buffering=false for queries
Dapper Contrib
• Generates SQL for simple CRUD operations
Questions?
Check out my blog posts
http://bit.ly/dapperseries
www.davepaquette.com
westerndevs.com
aspnetmonsters.com
Blog(s)
Twitter @Dave_Paquette
Email contactme@davepaquette.com
Thanks!
Ad

More Related Content

What's hot (20)

Dapper performance
Dapper performanceDapper performance
Dapper performance
Suresh Loganatha
 
ADO.NET Entity Framework
ADO.NET Entity FrameworkADO.NET Entity Framework
ADO.NET Entity Framework
Doncho Minkov
 
Spring boot introduction
Spring boot introductionSpring boot introduction
Spring boot introduction
Rasheed Waraich
 
Windows 10 Nt Heap Exploitation (English version)
Windows 10 Nt Heap Exploitation (English version)Windows 10 Nt Heap Exploitation (English version)
Windows 10 Nt Heap Exploitation (English version)
Angel Boy
 
What's New in Apache Hive
What's New in Apache HiveWhat's New in Apache Hive
What's New in Apache Hive
DataWorks Summit
 
Learning ASP.NET 5 and MVC 6
Learning ASP.NET 5 and MVC 6Learning ASP.NET 5 and MVC 6
Learning ASP.NET 5 and MVC 6
Ido Flatow
 
PostgreSQL Materialized Views with Active Record
PostgreSQL Materialized Views with Active RecordPostgreSQL Materialized Views with Active Record
PostgreSQL Materialized Views with Active Record
David Roberts
 
Exception handling
Exception handlingException handling
Exception handling
Anna Pietras
 
Apache Spark & Streaming
Apache Spark & StreamingApache Spark & Streaming
Apache Spark & Streaming
Fernando Rodriguez
 
PySpark Programming | PySpark Concepts with Hands-On | PySpark Training | Edu...
PySpark Programming | PySpark Concepts with Hands-On | PySpark Training | Edu...PySpark Programming | PySpark Concepts with Hands-On | PySpark Training | Edu...
PySpark Programming | PySpark Concepts with Hands-On | PySpark Training | Edu...
Edureka!
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with Spring
Joshua Long
 
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js + Expres...
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js +  Expres...Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js +  Expres...
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js + Expres...
Edureka!
 
Designing Structured Streaming Pipelines—How to Architect Things Right
Designing Structured Streaming Pipelines—How to Architect Things RightDesigning Structured Streaming Pipelines—How to Architect Things Right
Designing Structured Streaming Pipelines—How to Architect Things Right
Databricks
 
How to Design Indexes, Really
How to Design Indexes, ReallyHow to Design Indexes, Really
How to Design Indexes, Really
Karwin Software Solutions LLC
 
CanSecWest 2017 - Port(al) to the iOS Core
CanSecWest 2017 - Port(al) to the iOS CoreCanSecWest 2017 - Port(al) to the iOS Core
CanSecWest 2017 - Port(al) to the iOS Core
Stefan Esser
 
Meet Up - Spark Stream Processing + Kafka
Meet Up - Spark Stream Processing + KafkaMeet Up - Spark Stream Processing + Kafka
Meet Up - Spark Stream Processing + Kafka
Knoldus Inc.
 
AWS 환경에서 MySQL BMT
AWS 환경에서 MySQL BMTAWS 환경에서 MySQL BMT
AWS 환경에서 MySQL BMT
I Goo Lee
 
Deep Dive into Stateful Stream Processing in Structured Streaming with Tathag...
Deep Dive into Stateful Stream Processing in Structured Streaming with Tathag...Deep Dive into Stateful Stream Processing in Structured Streaming with Tathag...
Deep Dive into Stateful Stream Processing in Structured Streaming with Tathag...
Databricks
 
Migrating Apache Spark ML Jobs to Spark + Tensorflow on Kubeflow
Migrating Apache Spark ML Jobs to Spark + Tensorflow on KubeflowMigrating Apache Spark ML Jobs to Spark + Tensorflow on Kubeflow
Migrating Apache Spark ML Jobs to Spark + Tensorflow on Kubeflow
Databricks
 
Real-time Analytics with Apache Flink and Druid
Real-time Analytics with Apache Flink and DruidReal-time Analytics with Apache Flink and Druid
Real-time Analytics with Apache Flink and Druid
Jan Graßegger
 
ADO.NET Entity Framework
ADO.NET Entity FrameworkADO.NET Entity Framework
ADO.NET Entity Framework
Doncho Minkov
 
Spring boot introduction
Spring boot introductionSpring boot introduction
Spring boot introduction
Rasheed Waraich
 
Windows 10 Nt Heap Exploitation (English version)
Windows 10 Nt Heap Exploitation (English version)Windows 10 Nt Heap Exploitation (English version)
Windows 10 Nt Heap Exploitation (English version)
Angel Boy
 
Learning ASP.NET 5 and MVC 6
Learning ASP.NET 5 and MVC 6Learning ASP.NET 5 and MVC 6
Learning ASP.NET 5 and MVC 6
Ido Flatow
 
PostgreSQL Materialized Views with Active Record
PostgreSQL Materialized Views with Active RecordPostgreSQL Materialized Views with Active Record
PostgreSQL Materialized Views with Active Record
David Roberts
 
Exception handling
Exception handlingException handling
Exception handling
Anna Pietras
 
PySpark Programming | PySpark Concepts with Hands-On | PySpark Training | Edu...
PySpark Programming | PySpark Concepts with Hands-On | PySpark Training | Edu...PySpark Programming | PySpark Concepts with Hands-On | PySpark Training | Edu...
PySpark Programming | PySpark Concepts with Hands-On | PySpark Training | Edu...
Edureka!
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with Spring
Joshua Long
 
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js + Expres...
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js +  Expres...Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js +  Expres...
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js + Expres...
Edureka!
 
Designing Structured Streaming Pipelines—How to Architect Things Right
Designing Structured Streaming Pipelines—How to Architect Things RightDesigning Structured Streaming Pipelines—How to Architect Things Right
Designing Structured Streaming Pipelines—How to Architect Things Right
Databricks
 
CanSecWest 2017 - Port(al) to the iOS Core
CanSecWest 2017 - Port(al) to the iOS CoreCanSecWest 2017 - Port(al) to the iOS Core
CanSecWest 2017 - Port(al) to the iOS Core
Stefan Esser
 
Meet Up - Spark Stream Processing + Kafka
Meet Up - Spark Stream Processing + KafkaMeet Up - Spark Stream Processing + Kafka
Meet Up - Spark Stream Processing + Kafka
Knoldus Inc.
 
AWS 환경에서 MySQL BMT
AWS 환경에서 MySQL BMTAWS 환경에서 MySQL BMT
AWS 환경에서 MySQL BMT
I Goo Lee
 
Deep Dive into Stateful Stream Processing in Structured Streaming with Tathag...
Deep Dive into Stateful Stream Processing in Structured Streaming with Tathag...Deep Dive into Stateful Stream Processing in Structured Streaming with Tathag...
Deep Dive into Stateful Stream Processing in Structured Streaming with Tathag...
Databricks
 
Migrating Apache Spark ML Jobs to Spark + Tensorflow on Kubeflow
Migrating Apache Spark ML Jobs to Spark + Tensorflow on KubeflowMigrating Apache Spark ML Jobs to Spark + Tensorflow on Kubeflow
Migrating Apache Spark ML Jobs to Spark + Tensorflow on Kubeflow
Databricks
 
Real-time Analytics with Apache Flink and Druid
Real-time Analytics with Apache Flink and DruidReal-time Analytics with Apache Flink and Druid
Real-time Analytics with Apache Flink and Druid
Jan Graßegger
 

Similar to Advanced data access with Dapper (20)

Advanced .NET Data Access with Dapper
Advanced .NET Data Access with Dapper Advanced .NET Data Access with Dapper
Advanced .NET Data Access with Dapper
David Paquette
 
Orms vs Micro-ORMs
Orms vs Micro-ORMsOrms vs Micro-ORMs
Orms vs Micro-ORMs
David Paquette
 
Dapper: the microORM that will change your life
Dapper: the microORM that will change your lifeDapper: the microORM that will change your life
Dapper: the microORM that will change your life
Davide Mauri
 
Object Relational Mapping with Dapper (Micro ORM)
Object Relational Mapping with Dapper (Micro ORM)Object Relational Mapping with Dapper (Micro ORM)
Object Relational Mapping with Dapper (Micro ORM)
Muhammad Umar
 
dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...
dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...
dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...
dotNet Miami
 
Entity Framework: Code First and Magic Unicorns
Entity Framework: Code First and Magic UnicornsEntity Framework: Code First and Magic Unicorns
Entity Framework: Code First and Magic Unicorns
Richie Rump
 
.NET Database Toolkit
.NET Database Toolkit.NET Database Toolkit
.NET Database Toolkit
wlscaudill
 
the .NET Framework. It provides the claf
the .NET Framework. It provides the clafthe .NET Framework. It provides the claf
the .NET Framework. It provides the claf
TesfahunMaru1
 
Ado .net
Ado .netAdo .net
Ado .net
Manish Singh
 
Object Relational Mapping In Real World Applications
Object Relational Mapping In Real World ApplicationsObject Relational Mapping In Real World Applications
Object Relational Mapping In Real World Applications
PhilWinstanley
 
MySQL, LINQ and the ADO_NET Entity Framework Presentation.ppt
MySQL, LINQ and the ADO_NET Entity Framework Presentation.pptMySQL, LINQ and the ADO_NET Entity Framework Presentation.ppt
MySQL, LINQ and the ADO_NET Entity Framework Presentation.ppt
hammadali341730
 
L2s 090701234157 Phpapp02
L2s 090701234157 Phpapp02L2s 090701234157 Phpapp02
L2s 090701234157 Phpapp02
google
 
Freeing Yourself from an RDBMS Architecture
Freeing Yourself from an RDBMS ArchitectureFreeing Yourself from an RDBMS Architecture
Freeing Yourself from an RDBMS Architecture
David Hoerster
 
Document databases
Document databasesDocument databases
Document databases
Qframe
 
Linq
LinqLinq
Linq
Easy Communication & Technology
 
ADO.NET
ADO.NETADO.NET
ADO.NET
Wani Zahoor
 
Introduction to ADO.NET
Introduction to ADO.NETIntroduction to ADO.NET
Introduction to ADO.NET
rchakra
 
Entity Framework Interview Questions PDF By ScholarHat
Entity Framework Interview Questions PDF By ScholarHatEntity Framework Interview Questions PDF By ScholarHat
Entity Framework Interview Questions PDF By ScholarHat
Scholarhat
 
The tortoise and the ORM
The tortoise and the ORMThe tortoise and the ORM
The tortoise and the ORM
Frikkie van Biljon
 
37c
37c37c
37c
Sireesh K
 
Advanced .NET Data Access with Dapper
Advanced .NET Data Access with Dapper Advanced .NET Data Access with Dapper
Advanced .NET Data Access with Dapper
David Paquette
 
Dapper: the microORM that will change your life
Dapper: the microORM that will change your lifeDapper: the microORM that will change your life
Dapper: the microORM that will change your life
Davide Mauri
 
Object Relational Mapping with Dapper (Micro ORM)
Object Relational Mapping with Dapper (Micro ORM)Object Relational Mapping with Dapper (Micro ORM)
Object Relational Mapping with Dapper (Micro ORM)
Muhammad Umar
 
dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...
dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...
dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...
dotNet Miami
 
Entity Framework: Code First and Magic Unicorns
Entity Framework: Code First and Magic UnicornsEntity Framework: Code First and Magic Unicorns
Entity Framework: Code First and Magic Unicorns
Richie Rump
 
.NET Database Toolkit
.NET Database Toolkit.NET Database Toolkit
.NET Database Toolkit
wlscaudill
 
the .NET Framework. It provides the claf
the .NET Framework. It provides the clafthe .NET Framework. It provides the claf
the .NET Framework. It provides the claf
TesfahunMaru1
 
Object Relational Mapping In Real World Applications
Object Relational Mapping In Real World ApplicationsObject Relational Mapping In Real World Applications
Object Relational Mapping In Real World Applications
PhilWinstanley
 
MySQL, LINQ and the ADO_NET Entity Framework Presentation.ppt
MySQL, LINQ and the ADO_NET Entity Framework Presentation.pptMySQL, LINQ and the ADO_NET Entity Framework Presentation.ppt
MySQL, LINQ and the ADO_NET Entity Framework Presentation.ppt
hammadali341730
 
L2s 090701234157 Phpapp02
L2s 090701234157 Phpapp02L2s 090701234157 Phpapp02
L2s 090701234157 Phpapp02
google
 
Freeing Yourself from an RDBMS Architecture
Freeing Yourself from an RDBMS ArchitectureFreeing Yourself from an RDBMS Architecture
Freeing Yourself from an RDBMS Architecture
David Hoerster
 
Document databases
Document databasesDocument databases
Document databases
Qframe
 
Introduction to ADO.NET
Introduction to ADO.NETIntroduction to ADO.NET
Introduction to ADO.NET
rchakra
 
Entity Framework Interview Questions PDF By ScholarHat
Entity Framework Interview Questions PDF By ScholarHatEntity Framework Interview Questions PDF By ScholarHat
Entity Framework Interview Questions PDF By ScholarHat
Scholarhat
 
Ad

Recently uploaded (20)

Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdfKit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Wonjun Hwang
 
In-App Guidance_ Save Enterprises Millions in Training & IT Costs.pptx
In-App Guidance_ Save Enterprises Millions in Training & IT Costs.pptxIn-App Guidance_ Save Enterprises Millions in Training & IT Costs.pptx
In-App Guidance_ Save Enterprises Millions in Training & IT Costs.pptx
aptyai
 
Multi-Agent AI Systems: Architectures & Communication (MCP and A2A)
Multi-Agent AI Systems: Architectures & Communication (MCP and A2A)Multi-Agent AI Systems: Architectures & Communication (MCP and A2A)
Multi-Agent AI Systems: Architectures & Communication (MCP and A2A)
HusseinMalikMammadli
 
Slack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teamsSlack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teams
Nacho Cougil
 
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Wonjun Hwang
 
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Maarten Verwaest
 
AI-proof your career by Olivier Vroom and David WIlliamson
AI-proof your career by Olivier Vroom and David WIlliamsonAI-proof your career by Olivier Vroom and David WIlliamson
AI-proof your career by Olivier Vroom and David WIlliamson
UXPA Boston
 
MULTI-STAKEHOLDER CONSULTATION PROGRAM On Implementation of DNF 2.0 and Way F...
MULTI-STAKEHOLDER CONSULTATION PROGRAM On Implementation of DNF 2.0 and Way F...MULTI-STAKEHOLDER CONSULTATION PROGRAM On Implementation of DNF 2.0 and Way F...
MULTI-STAKEHOLDER CONSULTATION PROGRAM On Implementation of DNF 2.0 and Way F...
ICT Frame Magazine Pvt. Ltd.
 
論文紹介:"InfLoRA: Interference-Free Low-Rank Adaptation for Continual Learning" ...
論文紹介:"InfLoRA: Interference-Free Low-Rank Adaptation for Continual Learning" ...論文紹介:"InfLoRA: Interference-Free Low-Rank Adaptation for Continual Learning" ...
論文紹介:"InfLoRA: Interference-Free Low-Rank Adaptation for Continual Learning" ...
Toru Tamaki
 
Cybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and MitigationCybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and Mitigation
VICTOR MAESTRE RAMIREZ
 
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Christian Folini
 
DNF 2.0 Implementations Challenges in Nepal
DNF 2.0 Implementations Challenges in NepalDNF 2.0 Implementations Challenges in Nepal
DNF 2.0 Implementations Challenges in Nepal
ICT Frame Magazine Pvt. Ltd.
 
Digital Technologies for Culture, Arts and Heritage: Insights from Interdisci...
Digital Technologies for Culture, Arts and Heritage: Insights from Interdisci...Digital Technologies for Culture, Arts and Heritage: Insights from Interdisci...
Digital Technologies for Culture, Arts and Heritage: Insights from Interdisci...
Vasileios Komianos
 
Longitudinal Benchmark: A Real-World UX Case Study in Onboarding by Linda Bor...
Longitudinal Benchmark: A Real-World UX Case Study in Onboarding by Linda Bor...Longitudinal Benchmark: A Real-World UX Case Study in Onboarding by Linda Bor...
Longitudinal Benchmark: A Real-World UX Case Study in Onboarding by Linda Bor...
UXPA Boston
 
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Safe Software
 
Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)
Kaya Weers
 
Top Hyper-Casual Game Studio Services
Top  Hyper-Casual  Game  Studio ServicesTop  Hyper-Casual  Game  Studio Services
Top Hyper-Casual Game Studio Services
Nova Carter
 
UiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptx
UiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptxUiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptx
UiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptx
anabulhac
 
Harmonizing Multi-Agent Intelligence | Open Data Science Conference | Gary Ar...
Harmonizing Multi-Agent Intelligence | Open Data Science Conference | Gary Ar...Harmonizing Multi-Agent Intelligence | Open Data Science Conference | Gary Ar...
Harmonizing Multi-Agent Intelligence | Open Data Science Conference | Gary Ar...
Gary Arora
 
Building Connected Agents: An Overview of Google's ADK and A2A Protocol
Building Connected Agents:  An Overview of Google's ADK and A2A ProtocolBuilding Connected Agents:  An Overview of Google's ADK and A2A Protocol
Building Connected Agents: An Overview of Google's ADK and A2A Protocol
Suresh Peiris
 
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdfKit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Wonjun Hwang
 
In-App Guidance_ Save Enterprises Millions in Training & IT Costs.pptx
In-App Guidance_ Save Enterprises Millions in Training & IT Costs.pptxIn-App Guidance_ Save Enterprises Millions in Training & IT Costs.pptx
In-App Guidance_ Save Enterprises Millions in Training & IT Costs.pptx
aptyai
 
Multi-Agent AI Systems: Architectures & Communication (MCP and A2A)
Multi-Agent AI Systems: Architectures & Communication (MCP and A2A)Multi-Agent AI Systems: Architectures & Communication (MCP and A2A)
Multi-Agent AI Systems: Architectures & Communication (MCP and A2A)
HusseinMalikMammadli
 
Slack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teamsSlack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teams
Nacho Cougil
 
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Wonjun Hwang
 
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Maarten Verwaest
 
AI-proof your career by Olivier Vroom and David WIlliamson
AI-proof your career by Olivier Vroom and David WIlliamsonAI-proof your career by Olivier Vroom and David WIlliamson
AI-proof your career by Olivier Vroom and David WIlliamson
UXPA Boston
 
MULTI-STAKEHOLDER CONSULTATION PROGRAM On Implementation of DNF 2.0 and Way F...
MULTI-STAKEHOLDER CONSULTATION PROGRAM On Implementation of DNF 2.0 and Way F...MULTI-STAKEHOLDER CONSULTATION PROGRAM On Implementation of DNF 2.0 and Way F...
MULTI-STAKEHOLDER CONSULTATION PROGRAM On Implementation of DNF 2.0 and Way F...
ICT Frame Magazine Pvt. Ltd.
 
論文紹介:"InfLoRA: Interference-Free Low-Rank Adaptation for Continual Learning" ...
論文紹介:"InfLoRA: Interference-Free Low-Rank Adaptation for Continual Learning" ...論文紹介:"InfLoRA: Interference-Free Low-Rank Adaptation for Continual Learning" ...
論文紹介:"InfLoRA: Interference-Free Low-Rank Adaptation for Continual Learning" ...
Toru Tamaki
 
Cybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and MitigationCybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and Mitigation
VICTOR MAESTRE RAMIREZ
 
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Christian Folini
 
Digital Technologies for Culture, Arts and Heritage: Insights from Interdisci...
Digital Technologies for Culture, Arts and Heritage: Insights from Interdisci...Digital Technologies for Culture, Arts and Heritage: Insights from Interdisci...
Digital Technologies for Culture, Arts and Heritage: Insights from Interdisci...
Vasileios Komianos
 
Longitudinal Benchmark: A Real-World UX Case Study in Onboarding by Linda Bor...
Longitudinal Benchmark: A Real-World UX Case Study in Onboarding by Linda Bor...Longitudinal Benchmark: A Real-World UX Case Study in Onboarding by Linda Bor...
Longitudinal Benchmark: A Real-World UX Case Study in Onboarding by Linda Bor...
UXPA Boston
 
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Safe Software
 
Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)
Kaya Weers
 
Top Hyper-Casual Game Studio Services
Top  Hyper-Casual  Game  Studio ServicesTop  Hyper-Casual  Game  Studio Services
Top Hyper-Casual Game Studio Services
Nova Carter
 
UiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptx
UiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptxUiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptx
UiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptx
anabulhac
 
Harmonizing Multi-Agent Intelligence | Open Data Science Conference | Gary Ar...
Harmonizing Multi-Agent Intelligence | Open Data Science Conference | Gary Ar...Harmonizing Multi-Agent Intelligence | Open Data Science Conference | Gary Ar...
Harmonizing Multi-Agent Intelligence | Open Data Science Conference | Gary Ar...
Gary Arora
 
Building Connected Agents: An Overview of Google's ADK and A2A Protocol
Building Connected Agents:  An Overview of Google's ADK and A2A ProtocolBuilding Connected Agents:  An Overview of Google's ADK and A2A Protocol
Building Connected Agents: An Overview of Google's ADK and A2A Protocol
Suresh Peiris
 
Ad

Advanced data access with Dapper

  • 1. Advanced Data Access with Dapper @Dave_Paquette Microsoft MVP (ASP.NET/IIS) [email protected] http://www.davepaquette.com
  • 2. Data Access How did we get here? Why is this so hard? public class Foo { //…some properties } SQL Server
  • 3. Data Access in .NET • In the beginning there was System.Data • IDbConnection • IDbCommand • IDataReader • IDbTransaction
  • 4. Sytem.Data - Reading Records var results = new List<Employee>(); using (SqlConnection connection = new SqlConnection(Settings.ConnectionString)) { SqlCommand command = new SqlCommand(“SELECT * FROM Employees”, connection); connection.Open(); IDataReader reader = command.ExecuteReader(); while (reader.Read()) { results.Add(ReadSingleRow(reader)); } reader.Close(); } return results;
  • 5. The ORMs will save us • Hide details of database • Generate SQL based on object model and configuration • ChangeTracking • Complex mapping strategies • Many-to-many relationships • Inheritance
  • 7. ORM Pain Points • Black box code generation –What is going on? • Performance Problems • Eager Loading vs Lazy Loading • Complex Inheritance Chains • Dealing with disconnected entities (in a web context)
  • 8. The Micro-ORMs will save us! • Query --> Objects • Usually focused on speed • Light on features
  • 9. Popular Micro-ORMs • Dapper • PetaPOCO • Massive • Simple.Data
  • 10. Dapper • Used in production at Stack Exchange • Super fast and easy to use
  • 11. Performance of SELECT mapping over 500 iterations - POCO serialization Method Duration Hand coded (using a SqlDataReader) 47ms Dapper ExecuteMapperQuery 49ms ServiceStack.OrmLite (QueryById) 50ms PetaPoco 52ms BLToolkit 80ms SubSonic CodingHorror 107ms NHibernate SQL 104ms Linq 2 SQL ExecuteQuery 181ms Entity framework ExecuteStoreQuery 631ms https://github.com/StackExchange/dapper-dot-net#performance-of-select-mapping-over-500-iterations---dynamic-serialization
  • 12. How can it be that fast? • Dapper dynamically writes code for you • Emits IL code for tasks like loading a data reader into an object • https://github.com/StackExchange/Dapper/blo b/master/Dapper/SqlMapper.cs#L3078
  • 13. Dapper works on Database Connections A set of extension methods on IDbConnection Aircraft aircraft; using (var connection = new SqlConnection(_connectionString)) { await connection.OpenAsync(); //Optional var query = "SELECT * FROM Aircraft WHERE Id = @Id"; Aircraft aircraft = await connection.QuerySingleAsync<Aircraft>(query, new {Id = id}); }
  • 14. Querying Simple Objects Aircraft aircraft = await connection.QuerySingleAsync<Aircraft>(query, new {Id = id}); IEnumerable<Aircraft> aircraft = await connection.QueryAsync<Aircraft>(query);
  • 15. Loading Related Objects – Multi-Mapping • Write a single query that returns all the data in a single row scheduledFlights = await connection.QueryAsync<ScheduledFlight, Airport, ScheduledFlight>(query, (flight, airport) => { flight.Airport = airport; return flight; }, new{FromCode = from} );
  • 16. Multi-Mapping Caveats • Data duplication • Query returns a bloated data set • Multiple instances of an object that represent the same thing • This is totally fine forOne-to-One relationships • No duplication here
  • 17. Loading Related Objects – Multiple Queries • Get data using multiple queries and wire them up yourself • Still executed in a single command that returns multiple results sets using (var multi = await connection.QueryMultipleAsync(query, new{FromCode = from} )) { scheduledFlights = multi.Read<ScheduledFlight>(); var airports = multi.Read<Airport>().ToDictionary(a => a.Id); foreach(var flight in scheduledFlights) { flight.Airport = airports[flight.AirportId]; } }
  • 18. Multi-Mapping vs Multiple Queries 100 ScheduledFlight Records 1,000 ScheduledFlight Records Method Mean MultiMapping 926.5 us MultipleResultSets 705.9 us Method Mean MultiMapping 5.098 ms MultipleResultSets 2.809 ms
  • 19. Loading More Complex Object Graphs
  • 20. Loading More Complex Object Graphs
  • 21. Paging through large collections • Use an OFFSET FETCH query • Include a total count in the result SELECT * FROM Flight f INNER JOIN ScheduledFlight sf ON f.ScheduledFlightId = sf.Id ORDER BY Day, FlightNumber OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY SELECT COUNT(*) FROM Flight f INNER JOIN ScheduledFlight sf ON f.ScheduledFlightId = sf.Id
  • 22. Insert / Update / Delete • Use the ExecuteAsync method • Built-in support for batch inserts await connection.ExecuteAsync( @"INSERT INTO Flight(ScheduledFlightId, Day, ScheduledDeparture, ScheduledArrival) VALUES(@ScheduledFlightId, @Day, @ScheduledDeparture, @ScheduledArrival)", flights);
  • 23. Buffering •Working with really large result sets? • Consider setting buffering=false for queries
  • 24. Dapper Contrib • Generates SQL for simple CRUD operations
  • 25. Questions? Check out my blog posts http://bit.ly/dapperseries

Editor's Notes

  • #3: Data access has consumed such a huge amount of our time. - Why is that? - What is so hard about this?
  • #4: These 4 interfaces were in the original .NET framework. They have been the basis for ALL database access since then. Each database provider has an implementation of each of these interfaces (eg. SqlConnection) Every ORM or Micro-ORM written in .NET is based on these 4 interfaces.
  • #5: Show sample code for reading and writing data using the raw SQL
  • #6: Swinging the pendulum
  • #20: Demo Start with loading simply the first level (Airport + Arrival and Departure Flights) Using multi-mapping to load the ScheduledFlight info Use multi queries to also load each ScheduledFlight’s Arrival and Departure airports