SlideShare ist ein Scribd-Unternehmen logo
1 von 27
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
https://github.com/StackExchange/Dapper#performance
ORM Method Mean Allocated
LINQ to DB 'First (Compiled)' 78.75 us 2.66 KB
LINQ to DB Query<T> 80.38 us 6.87 KB
Hand Coded SqlCommand 87.16 us 12.24 KB
Dapper QueryFirstOrDefault<dynamic> 87.80 us 13.5 KB
Dapper QueryFirstOrDefault<T> 91.51 us 13.46 KB
Massive 'Query (dynamic)' 96.18 us 14.19 KB
PetaPoco 'Fetch<T> (Fast)' 96.57 us 13.65 KB
EF 6 SqlQuery 143.86 us 27.86 KB
EF Core 'First (Compiled)' 148.42 us 16.08 KB
NHibernate Get<T> 196.88 us 32.5 KB
EF Core First 197.91 us 20.25 KB
NHibernate HQL 207.84 us 35 KB
EF Core 'First (NoTracking)' 213.58 us 21.36 KB
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
https://www.davepaquette.com/archive/2018/04/10/loading-related-entities-many-to-one-part-2.aspx
AirportSchedule
Date
Airport
Departures
Arrivals
Airport
Id
Code
City
Province
Country
Flight
Id
ScheduledFlight
ScheduledDeparture
ActualDeparture
ScheduledArrival
ActualArrival
ScheduledFlight
Id
FlightNumber
DepartureAirport
ArrivalAirport
…
1
1
1
**
1
1
1
1
1
* *
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!

Weitere ähnliche Inhalte

Was ist angesagt?

오픈소스 WAS를 위한 클러스터 솔루션 - OPENMARU Cluster
오픈소스 WAS를 위한 클러스터 솔루션 - OPENMARU Cluster오픈소스 WAS를 위한 클러스터 솔루션 - OPENMARU Cluster
오픈소스 WAS를 위한 클러스터 솔루션 - OPENMARU Cluster
Opennaru, inc.
 
엔터프라이즈의 효과적인 클라우드 도입을 위한 전략 및 적용 사례-신규진 프로페셔널 서비스 리드, AWS/고병률 데이터베이스 아키텍트, 삼성...
엔터프라이즈의 효과적인 클라우드 도입을 위한 전략 및 적용 사례-신규진 프로페셔널 서비스 리드, AWS/고병률 데이터베이스 아키텍트, 삼성...엔터프라이즈의 효과적인 클라우드 도입을 위한 전략 및 적용 사례-신규진 프로페셔널 서비스 리드, AWS/고병률 데이터베이스 아키텍트, 삼성...
엔터프라이즈의 효과적인 클라우드 도입을 위한 전략 및 적용 사례-신규진 프로페셔널 서비스 리드, AWS/고병률 데이터베이스 아키텍트, 삼성...
Amazon Web Services Korea
 

Was ist angesagt? (20)

오픈소스 WAS를 위한 클러스터 솔루션 - OPENMARU Cluster
오픈소스 WAS를 위한 클러스터 솔루션 - OPENMARU Cluster오픈소스 WAS를 위한 클러스터 솔루션 - OPENMARU Cluster
오픈소스 WAS를 위한 클러스터 솔루션 - OPENMARU Cluster
 
[2018] 고객 사례를 통해 본 클라우드 전환 전략
[2018] 고객 사례를 통해 본 클라우드 전환 전략[2018] 고객 사례를 통해 본 클라우드 전환 전략
[2018] 고객 사례를 통해 본 클라우드 전환 전략
 
Spring boot
Spring bootSpring boot
Spring boot
 
Spring Framework Petclinic sample application
Spring Framework Petclinic sample applicationSpring Framework Petclinic sample application
Spring Framework Petclinic sample application
 
[GitOps] Argo CD on GKE (v0.9.2).pdf
[GitOps] Argo CD on GKE (v0.9.2).pdf[GitOps] Argo CD on GKE (v0.9.2).pdf
[GitOps] Argo CD on GKE (v0.9.2).pdf
 
엔터프라이즈의 효과적인 클라우드 도입을 위한 전략 및 적용 사례-신규진 프로페셔널 서비스 리드, AWS/고병률 데이터베이스 아키텍트, 삼성...
엔터프라이즈의 효과적인 클라우드 도입을 위한 전략 및 적용 사례-신규진 프로페셔널 서비스 리드, AWS/고병률 데이터베이스 아키텍트, 삼성...엔터프라이즈의 효과적인 클라우드 도입을 위한 전략 및 적용 사례-신규진 프로페셔널 서비스 리드, AWS/고병률 데이터베이스 아키텍트, 삼성...
엔터프라이즈의 효과적인 클라우드 도입을 위한 전략 및 적용 사례-신규진 프로페셔널 서비스 리드, AWS/고병률 데이터베이스 아키텍트, 삼성...
 
Introduction to Spring Cloud
Introduction to Spring Cloud           Introduction to Spring Cloud
Introduction to Spring Cloud
 
How Romanian companies are developing secure applications on Azure.pptx
How Romanian companies are developing secure applications on Azure.pptxHow Romanian companies are developing secure applications on Azure.pptx
How Romanian companies are developing secure applications on Azure.pptx
 
Oracle REST Data Services
Oracle REST Data ServicesOracle REST Data Services
Oracle REST Data Services
 
ECS+Locust로 부하 테스트 진행하기
ECS+Locust로 부하 테스트 진행하기ECS+Locust로 부하 테스트 진행하기
ECS+Locust로 부하 테스트 진행하기
 
Case Study: Migrating Hyperic from EJB to Spring from JBoss to Apache Tomcat
Case Study: Migrating Hyperic from EJB to Spring from JBoss to Apache TomcatCase Study: Migrating Hyperic from EJB to Spring from JBoss to Apache Tomcat
Case Study: Migrating Hyperic from EJB to Spring from JBoss to Apache Tomcat
 
주가 정보 다루기.pdf
주가 정보 다루기.pdf주가 정보 다루기.pdf
주가 정보 다루기.pdf
 
스프링캠프 2016 발표 - Deep dive into spring boot autoconfiguration
스프링캠프 2016 발표 - Deep dive into spring boot autoconfiguration스프링캠프 2016 발표 - Deep dive into spring boot autoconfiguration
스프링캠프 2016 발표 - Deep dive into spring boot autoconfiguration
 
Ch02 撰寫與設定 Servlet
Ch02 撰寫與設定 ServletCh02 撰寫與設定 Servlet
Ch02 撰寫與設定 Servlet
 
[오픈소스컨설팅] Docker를 활용한 Gitlab CI/CD 구성 테스트
[오픈소스컨설팅] Docker를 활용한 Gitlab CI/CD 구성 테스트[오픈소스컨설팅] Docker를 활용한 Gitlab CI/CD 구성 테스트
[오픈소스컨설팅] Docker를 활용한 Gitlab CI/CD 구성 테스트
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
An Overview about open UDP Services
An Overview about open UDP ServicesAn Overview about open UDP Services
An Overview about open UDP Services
 
Rabbitmq
RabbitmqRabbitmq
Rabbitmq
 
스프링 시큐리티 구조 이해
스프링 시큐리티 구조 이해스프링 시큐리티 구조 이해
스프링 시큐리티 구조 이해
 
IBMが新しいJava EEコンテナを作っているらしい -Libertyプロファイルとは-
IBMが新しいJava EEコンテナを作っているらしい -Libertyプロファイルとは-IBMが新しいJava EEコンテナを作っているらしい -Libertyプロファイルとは-
IBMが新しいJava EEコンテナを作っているらしい -Libertyプロファイルとは-
 

Ähnlich wie Advanced .NET Data Access with Dapper

nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.ppt
WalaSidhom1
 
Hw09 Sqoop Database Import For Hadoop
Hw09   Sqoop Database Import For HadoopHw09   Sqoop Database Import For Hadoop
Hw09 Sqoop Database Import For Hadoop
Cloudera, Inc.
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
Tom Croucher
 
Breaking Parser Logic: Take Your Path Normalization Off and Pop 0days Out!
Breaking Parser Logic: Take Your Path Normalization Off and Pop 0days Out!Breaking Parser Logic: Take Your Path Normalization Off and Pop 0days Out!
Breaking Parser Logic: Take Your Path Normalization Off and Pop 0days Out!
Priyanka Aash
 
OWB11gR2 - Extending ETL
OWB11gR2 - Extending ETL OWB11gR2 - Extending ETL
OWB11gR2 - Extending ETL
Suraj Bang
 

Ähnlich wie Advanced .NET Data Access with Dapper (20)

Advanced data access with Dapper
Advanced data access with DapperAdvanced data access with Dapper
Advanced data access with Dapper
 
Orms vs Micro-ORMs
Orms vs Micro-ORMsOrms vs Micro-ORMs
Orms vs Micro-ORMs
 
JDBC Connecticity.ppt
JDBC Connecticity.pptJDBC Connecticity.ppt
JDBC Connecticity.ppt
 
Play framework productivity formula
Play framework   productivity formula Play framework   productivity formula
Play framework productivity formula
 
Spark etl
Spark etlSpark etl
Spark etl
 
UEMB200: Next Generation of Endpoint Management Architecture and Discovery Se...
UEMB200: Next Generation of Endpoint Management Architecture and Discovery Se...UEMB200: Next Generation of Endpoint Management Architecture and Discovery Se...
UEMB200: Next Generation of Endpoint Management Architecture and Discovery Se...
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.ppt
 
Hw09 Sqoop Database Import For Hadoop
Hw09   Sqoop Database Import For HadoopHw09   Sqoop Database Import For Hadoop
Hw09 Sqoop Database Import For Hadoop
 
NoSQL meets Microservices - Michael Hackstein
NoSQL meets Microservices -  Michael HacksteinNoSQL meets Microservices -  Michael Hackstein
NoSQL meets Microservices - Michael Hackstein
 
Keeping Spark on Track: Productionizing Spark for ETL
Keeping Spark on Track: Productionizing Spark for ETLKeeping Spark on Track: Productionizing Spark for ETL
Keeping Spark on Track: Productionizing Spark for ETL
 
Zend Con 2008 Slides
Zend Con 2008 SlidesZend Con 2008 Slides
Zend Con 2008 Slides
 
Complex Made Simple: Sleep Better with TorqueBox
Complex Made Simple: Sleep Better with TorqueBoxComplex Made Simple: Sleep Better with TorqueBox
Complex Made Simple: Sleep Better with TorqueBox
 
Sherlock Homepage (Maarten Balliauw)
Sherlock Homepage (Maarten Balliauw)Sherlock Homepage (Maarten Balliauw)
Sherlock Homepage (Maarten Balliauw)
 
Sherlock Homepage - A detective story about running large web services (VISUG...
Sherlock Homepage - A detective story about running large web services (VISUG...Sherlock Homepage - A detective story about running large web services (VISUG...
Sherlock Homepage - A detective story about running large web services (VISUG...
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
Breaking Parser Logic: Take Your Path Normalization Off and Pop 0days Out!
Breaking Parser Logic: Take Your Path Normalization Off and Pop 0days Out!Breaking Parser Logic: Take Your Path Normalization Off and Pop 0days Out!
Breaking Parser Logic: Take Your Path Normalization Off and Pop 0days Out!
 
Sherlock Homepage - A detective story about running large web services - NDC ...
Sherlock Homepage - A detective story about running large web services - NDC ...Sherlock Homepage - A detective story about running large web services - NDC ...
Sherlock Homepage - A detective story about running large web services - NDC ...
 
Web program-peformance-optimization
Web program-peformance-optimizationWeb program-peformance-optimization
Web program-peformance-optimization
 
OWB11gR2 - Extending ETL
OWB11gR2 - Extending ETL OWB11gR2 - Extending ETL
OWB11gR2 - Extending ETL
 
Nodejs - A quick tour (v6)
Nodejs - A quick tour (v6)Nodejs - A quick tour (v6)
Nodejs - A quick tour (v6)
 

Kürzlich hochgeladen

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Kürzlich hochgeladen (20)

ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 

Advanced .NET Data Access with Dapper

  • 1. Advanced Data Access with Dapper @Dave_Paquette Microsoft MVP (ASP.NET/IIS) contactme@davepaquette.com http://www.davepaquette.com
  • 2.
  • 3. Data Access How did we get here? Why is this so hard? public class Foo { //…some properties } SQL Server
  • 4. Data Access in .NET • In the beginning there was System.Data • IDbConnection • IDbCommand • IDataReader • IDbTransaction
  • 5. 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;
  • 6. 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
  • 8. 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)
  • 9. The Micro-ORMs will save us! • Query --> Objects • Usually focused on speed • Light on features
  • 10. Popular Micro-ORMs • Dapper • PetaPOCO • Massive • Simple.Data
  • 11. Dapper • Used in production at Stack Exchange • Super fast and easy to use
  • 12. Performance of SELECT mapping over 500 iterations - POCO serialization https://github.com/StackExchange/Dapper#performance ORM Method Mean Allocated LINQ to DB 'First (Compiled)' 78.75 us 2.66 KB LINQ to DB Query<T> 80.38 us 6.87 KB Hand Coded SqlCommand 87.16 us 12.24 KB Dapper QueryFirstOrDefault<dynamic> 87.80 us 13.5 KB Dapper QueryFirstOrDefault<T> 91.51 us 13.46 KB Massive 'Query (dynamic)' 96.18 us 14.19 KB PetaPoco 'Fetch<T> (Fast)' 96.57 us 13.65 KB EF 6 SqlQuery 143.86 us 27.86 KB EF Core 'First (Compiled)' 148.42 us 16.08 KB NHibernate Get<T> 196.88 us 32.5 KB EF Core First 197.91 us 20.25 KB NHibernate HQL 207.84 us 35 KB EF Core 'First (NoTracking)' 213.58 us 21.36 KB
  • 13. 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
  • 14. 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}); }
  • 15. Querying Simple Objects Aircraft aircraft = await connection.QuerySingleAsync<Aircraft>(query, new {Id = id}); IEnumerable<Aircraft> aircraft = await connection.QueryAsync<Aircraft>(query);
  • 16. 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} );
  • 17. 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
  • 18. 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]; } }
  • 19. 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 https://www.davepaquette.com/archive/2018/04/10/loading-related-entities-many-to-one-part-2.aspx
  • 21. Loading More Complex Object Graphs
  • 22. 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
  • 23. 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);
  • 24. Buffering •Working with really large result sets? • Consider setting buffering=false for queries
  • 25. Dapper Contrib • Generates SQL for simple CRUD operations
  • 26. Questions? Check out my blog posts http://bit.ly/dapperseries

Hinweis der Redaktion

  1. Data access has consumed such a huge amount of our time. - Why is that? - What is so hard about this?
  2. 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.
  3. Show sample code for reading and writing data using the raw SQL
  4. Swinging the pendulum
  5. 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