Thank you to our AWESOME sponsors!

Slides:



Advertisements
Similar presentations
Introduction to NHibernate By Andrew Smith. The Basics Object Relation Mapper Maps POCOs to database tables Based on Java Hibernate. V stable Generates.
Advertisements

Yukon – What is New Rajesh Gala. Yukon – What is new.NET Framework Programming Data Types Exception Handling Batches Databases Database Engine Administration.
17. Data Access ADO.Net Architecture New Features of ADO.NET
Michael Pizzo Software Architect Data Programmability Microsoft Corporation.
ASP.NET Best Practices Dawit Wubshet Park University.
.NET 3.5 – Mysteries. NetFx Evolution NetFx 1.0 C# 1.0, VB 7.0, VS.NET NetFx 1.1 C# 1.1, VB 7.1, VS 2003 NetFx 2.0 C# 2.0, VB 8.0, VS 2005 NetFx 3.0 C#
.NET Database Technologies: Open-Source Frameworks.
Object Relational Mapping A to Z. About Me Over A Decade of I.T. Experience Web Developer, DBA, DevOps, Mobile Microsoft Cert. in SQL Server Twitter:
WCF RIA Services - Querying and Updating Data SILVERLIGHTSHOW.NET WEBINARS SERIES BRIAN NOYES, CHIEF ARCHITECT, IDESIGN INC 2 FEB 2011.
A tour of new features introducing LINQ. Agenda of LINQ Presentation We have features for every step of the way LINQ Fundamentals Anonymous Functions/Lambda.
Phonegap Bridge – File System CIS 136 Building Mobile Apps 1.
In C# program Before you can start using the ODBC class definitions, you will need to include the right module. using System.Data.Odbc; // ODBC definitions.
Entity Framework Code First End to End
The Tip of the ADO-burg Francisco H Tapia. Ado Objects Command Connection Error Parameter Property Record RecordSet Stream.
NHibernate in Action Web Seminar at UMLChina By Pierre Henri Kuaté 2008/08/27
ADO.NET A2 Teacher Up skilling LECTURE 3. What’s to come today? ADO.NET What is ADO.NET? ADO.NET Objects SqlConnection SqlCommand SqlDataReader DataSet.
Accessing SQL Server and OLE DB from.NET Svetlin Nakov Telerik Corporation
Lecture Set 14 B new Introduction to Databases - Database Processing: The Connected Model (Using DataReaders)
Lecture 4 PL/SQL language. PL/SQL – procedural SQL Allows combining procedural and SQL code PL/SQL code is compiled, including SQL commands PL/SQL code.
Tom Castiglia Hershey Technologies
CHAPTER:14 Simple Queries in SQL Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्सजेंड़र ) PGT(CS),KV JHAGRAKHAND.
Databases and Data Access  Introduction to ADO.NET  ADO.NET objects  ADP.NET namespaces  Differences between ADO and ADO.NET.
ADO.Net CS795. What is ADO.Net? Database language spoken by managed applications ADO.net database accesses go through modules: data providers –SQL Server.Net.
Programming using C# Joins SQL Injection Stored Procedures
Hibernate 3.0. What is Hibernate Hibernate is a free, open source Java package that makes it easy to work with relational databases. Hibernate makes it.
8 1 Chapter 8 Advanced SQL Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
 It is the primary data access model for.Net applications  Next version of ADO  Can be divided into two parts ◦ Providers ◦ DataSets  Resides in System.Data.
Chapter 8 Advanced SQL Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
DAT430 Extending Microsoft ® ADO.NET Building a Custom Data Factory API DAT430 Extending Microsoft ® ADO.NET Building a Custom Data Factory API Gert E.R.
ADO.Net CS795. What is ADO.Net? Database language spoken by managed applications ADO.net database accesses go through modules: data providers –SQL Server.Net.
Module 4 Introduction ADO.NET.
C# .NET Software Development
Active Data Objects Using.Net ADO.Net Farooq Ahmed Amna Umber Summayya Shehzad.
IMS 4212: Application Architecture and Intro to Stored Procedures 1 Dr. Lawrence West, Management Dept., University of Central Florida
Ch 7. Working with relational data. Transactions Group of statements executed as a group. If all statements execute successfully, changes are committed.
By Shantanu Narang CS 157b. Relational Model  Object Model Object Oriented Databases(OOD) Object Query Language(OQL) OOD pros and cons.
CS 440 Database Management Systems Stored procedures & OR mapping 1.
By Durga Dasari. DbFit - DB Unit and Integration test tool  Test-driven database development. Write readable, easy- to-maintain unit and integration.
ADO .NET from. ADO .NET from “ADO .Net” Evolution/History of ADO.NET MICROSOFT .NET “ADO .Net” Evolution/History of ADO.NET History: Most applications.
.NET Data Access and Manipulation
CSC314 DAY 9 Intermediate SQL 1. Chapter 6 © 2013 Pearson Education, Inc. Publishing as Prentice Hall USING AND DEFINING VIEWS  Views provide users controlled.
Creating Database Objects
Introduction to Entity framework
Introduction to Entity Framework
Relational Model.
Prepared by : Moshira M. Ali CS490 Coordinator Arab Open University
Overview of Data Access
Entity Framework By: Casey Griffin.
Learn. Imagine. Build. .NET Conf
ADO.NET Entity Framework
Overview of Data Access
An Introduction to Entity Framework
ORMs and the DBA How to Make Both Happy.
Lecture Set 14 B new Introduction to Databases - Database Processing: The Connected Model (Using DataReaders)
In the name of the resources
Entity Framework Core (EF Core)
ORMs and the DBA How to Make Both Happy.
ORMs and the DBA How to Make Both Happy.
Chapter 8 Advanced SQL.
Entity Framework Core for Enterprise Applications
SQL Server Query Design and Optimization Recommendations
SQL – Application Persistence Design Patterns
Creating Database Objects
M S COLLEGE OF ART’S, COMM., SCI. & BMS Advance Web Programming
06 | Integrating extra features and looking forward
Why should I care about SQL, if I have ORM?
Entity Framework & LINQ (Language Integrated Query)
SPL – PS13 Persistence Layer.
Presentation transcript:

Thank you to our AWESOME sponsors!

Dejan Dular, Dejan dular s.p. dapper adjective (of a man) neat and trim in dress and appearance. "he looked very dapper in a dark silk suit" Dapper the Micro-ORM Dejan Dular, Dejan dular s.p.

About me Dejan Dular Dejan Dular s.p. .NET Developer SQL enthusiast Twitter: @dejandular Mail: dejan@majolka.com LinkedIn: dejandular Dejan Dular Dejan Dular s.p. .NET Developer SQL enthusiast Dynamics CRM specialist IoT fan DIY & eco maniac

What are we looking at? High performance Micro-ORM Very light POCO support Easy to implement – extension of IDbConnection interface Works across all .NET ADO providers very performance more easy such lightweight Dynamic method generation ExpandoObject POCO Wow much providers

Demo Difference between using SqlDataReader and Dapper

IDbConnection extension methods connection.Query public static IEnumerable<T> Query<T>(this IDbConnection cnn, string sql, object param = null, SqlTransaction transaction = null, bool buffered = true) public static IEnumerable<dynamic> Query(this IDbConnection cnn, string sql, object param = null, SqlTransaction transaction = null, bool buffered = true) connection.Execute public static int Execute(this IDbConnection cnn, string sql, object param = null, SqlTransaction transaction = null) connection.ExecuteScalar public static T ExecuteScalar<T>(this IDbConnection cnn, string sql, object param = null, SqlTransaction transaction = null)

Parameterized queries Parameters are passed in as anonymous classes. connection.Query("SELECT * FROM theTable WHERE a = @A and b = @b", new {A = 1, B = "b"});

Demo 1, 2, 3 Parametrized queries

List Support IEnumerable will automatically parameterize your query. connection.Query("select * from theTable where Id in @Ids", new { Ids = new int[] { 1, 2, 3 }}); …where Id in (@Ids1, @Ids2, @Ids3)" // @Ids1=1, @Ids2=2, @Ids3=3

Run query multiple times conn.Execute("INSERT INTO tmpTest(Id, Val) VALUES (@Id, @Val)", new [] { new { Id = 1, Val = "a" }, new { Id = 2, Val = "b" }, new { Id = 3, Val = "c" } });

Demo 4 Bulk loading

Multi Mapping Load data from a single row to multiple objects. If the identity column is not named ID, use SplitOn attribute Supports up to 7 joined tables IEnumerable<TReturn> Query<TFirst, TSecond, …, TReturn>(this IDbConnection cnn, string sql, Func<TFirst, TSecond, …, TReturn> map, dynamic param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null, CommandType? commandType = null)

Demo 5 Multi mapping

Multiple results var sql = @" select * from Customers where CustomerId = @id select * from Orders where CustomerId = @id select * from Returns where CustomerId = @id"; using (var multi = connection.QueryMultiple(sql, new {id=selectedId})) { var customer = multi.Read<Customer>().Single(); var orders = multi.Read<Order>().ToList(); var returns = multi.Read<Return>().ToList(); ... }

Demo 6 Multiple results

Stored procedures var p = new Dapper.DynamicParameters(); p.Add("@a", 11); p.Add("@b", dbType: DbType.Int32, direction: ParameterDirection.Output); p.Add("@c", dbType: DbType.Int32, direction: ParameterDirection.ReturnValue); conn.Execute("spMagicProc", p, commandType: commandType.StoredProcedure); int b = p.Get<int>("@b"); int c = p.Get<int>("@c"); Instead of conn.Execute you can call conn.Query if the stored procedure returns a record set.

Demo 8 Stored procedures

Also worth mentioning (IDataReader) ExcuteReader AsTableValuedParameter(this DataTable…) Query cache management functions Buffering async / await support

Demo 9 Asynchronous functions

Be careful! By default Dapper buffers the entire reader on return. Set the “buffered” parameter to false if you want to load objects as needed. If the connection is closed, Dapper opens it and closes it at the end of the command execution. Opened connections are left open. If all values can be mapped, object is created even if all are NULL. Read multiple results in the same order as defined in the SQL query.

Be careful … more varchar VS nvarchar: To query non Unicode use ANSI : Query<Thing>("select * from Thing where Name = @Name", new {Name = new DbString{Value="abcde", IsFixedLength=true, Length=10, IsAnsi=true }); Due to query information caching you can hit memory issues if you are generating SQL strings on the fly without using parameters. Further versions may fix this. Class must have a default constructor or a construction that will exactly match the type and order of the columns in the query.

What is not there No identity map, there are no helpers for update / select, … Hey! It’s micro ORM

Micro ORM vs ORM Features Entity Framework Dapper POCO Yes Second level cache No Relationships No* Designer Migration Learning curve Slow Fast Performance Meh* Awww yeah! Second-level caches are instrumental in solving this type of problem. These caches exist outside of the transaction—often outside of the application—and therefore are available to any context instance. And second-level caching is a commonly used coding pattern for caching data for various uses.

Micro ORM vs ORM Speed Entity Framework Dapper Run First Second Load 1 record by ID 335 13 72 7 Load many by string 75 34 8 Performing JOIN 134 37 23 19 Inserting 264 12 86 http://www.dontpaniclabs.com/blog/post/2014/05/01/Speed-Comparison-Dapper-vs-Entity-Framework/

Micro ORM vs ORM Speed SELECT mapping over 500 iterations (POCO serialization) Method Duration Hand coded (using a SqlDataReader) 47ms Dapper ExecuteMapperQuery 49ms PetaPoco 52ms NHibernate SQL 104ms Linq 2 SQL ExecuteQuery 181ms Entity Framework ExecuteStoreQuery 631ms https://github.com/StackExchange/dapper-dot-net

https://noamlewis. wordpress https://noamlewis.wordpress.com/2012/07/18/net-4-5-improves-orm-performance-across-the-chart/

What to use? EF Dapper Small projects, demo applications, tests Working with relationships Data layer performance Legacy code with SqlDataReader Big projects with complex repository Bulk data transfers You have a DBA living inside you (a hidden personality) and want to optimize transactions SqlBulkCopy

Demo Developing a Dapper extension

Links Dapper: https://github.com/StackExchange/dapper-dot-net/ Dapper Contrib: https://github.com/StackExchange/dapper-dot-net/tree/master/Dapper.Contrib Dapper Rainbow: https://github.com/StackExchange/dapper-dot-net/tree/master/Dapper.Rainbow Dapper Extensions: https://github.com/tmsmith/Dapper-Extensions Dapper SimpleSave: https://github.com/Paymentsense/Dapper.SimpleSave Dapper SimpleLoad: https://github.com/Paymentsense/Dapper.SimpleLoad Some micro ORM alternatives: Massive https://github.com/FransBouma/Massive PetaPoco http://www.toptensoftware.com/petapoco/ FluentData http://fluentdata.codeplex.com/ Simple.Data https://github.com/markrendle/Simple.Data SubSonic http://subsonicproject.com/ 5 reasons not to use micro ORM: http://www.mindscapehq.com/blog/index.php/2011/12/05/5-reasons-not-to-use-a-micro-orm/ Contrib – CRUD, change tracking Rainbow – CRUD, Extensions – CRUD, Paging SimpleSave, SimpleLoad – Complex objects Massive, PetaPoco – only dynamic objects FluentData – contexts, CRUD, dynamic, but own mappers Simple.Data – NoSQL support Subsonic – Batman Ustility Belt for Data Layer

try { EndPresentation(); } catch(QuestionsException q) AnswerQuestions(q); Twitter: @dejandular Mail: dejan@majolka.com LinkedIn: dejandular finally { var attendees = connection.Query("SELECT Name FROM Attendees"); attendees.All(a => { Console.WriteLine($"Thank you {a.Name}!"); return true; }); }