SlideShare a Scribd company logo
Simple Object Mapping
pour SQL Databases
Développer simplement et rapidement
dvoituron@outlook.com
www.dvoituron.com
@DenisVoituron
2
A propos…
Denis Voituron
1995 – Ingénieur Civil
1999 – Co-fondateur d’une société spécialisée dans les CMS
2007 – Microsoft Senior Architect chez Trasys / NRB
2
@DenisVoituron
dvoituron.com
.be
3
Agenda
• Background
• SQL Architecture
• ADO.NET
• EntityFramework
• Comparaison
• Simple Object Mapping
• Dapper.NET
• SqlDatabaseCommand
• SQLite
• SQL Server CLR Stored Procedures
3
Backgound
5
Architecture
SCOTT Database
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7839 KING PRESIDENT 17-NOV-81 5000 10
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7756 CLARK MANAGER 7839 09-JUN-81 1500 10
... ...
... ...
7456 JONES MANAGER 7839 02-APR-81 2975 20
DEPTNO DNAME LOC
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIOS BOSTON
7
ADO.NET
7
using (var connection = new SqlConnection(CONNECTION_STRING))
{
connection.Open();
connection.Close();
}
SELECT ENAME FROM EMP WHERE EMPNO = 7369
using (var cmd = connection.CreateCommand())
{
cmd.CommandText = "SELECT ENAME " +
" FROM EMP " +
" WHERE EMPNO = 7369 ";
}
using (var adapter = new SqlDataAdapter(cmd))
{
DataTable table = new DataTable();
adapter.Fill(table);
string name = table.Rows[0].Field<string>("ENAME");
}
8
Entity Framework
8
Object Relational Mapping
var db = new SCOTTEntities();
var query = from e in db.EMPs
where e.EMPNO == 7369
select e;
var name = query.First().DEPT.DNAME;
SELECT TOP (1)
[Extent1].[EMPNO] AS [EMPNO],
[Extent1].[ENAME] AS [ENAME],
[Extent1].[JOB] AS [JOB],
[Extent1].[MGR] AS [MGR],
[Extent1].[HIREDATE] AS [HIREDATE],
[Extent1].[SAL] AS [SAL],
[Extent1].[COMM] AS [COMM],
[Extent1].[DEPTNO] AS [DEPTNO]
FROM [dbo].[EMP] AS [Extent1]
WHERE 7369 = [Extent1].[EMPNO]
SELECT
[Extent1].[DEPTNO] AS [DEPTNO],
[Extent1].[DNAME] AS [DNAME],
[Extent1].[LOC] AS [LOC]
FROM [dbo].[DEPT] AS [Extent1]
WHERE [Extent1].[DEPTNO] = @V1
9
ADO.NET vs Entity Framework
9
Performance
Speed of Development
Maintainable code (neat)
Flexibility
Scalability
http://stackoverflow.com/questions/2698151/entity-framework-vs-linq-to-sql-vs-ado-net-with-stored-procedures
10
Performances
10http://blogs.msdn.com/b/adonet/archive/2012/02/14/sneak-preview-entity-framework-5-0-performance-improvements.aspx
Simple Object Mapping
12
Dapper.NET
Bibliothèque qui étend IDbConnection.
Besoin d’une connexion déjà ouverte.
using (var connection = new SqlConnection(CONNECTION_STRING))
{
connection.Open();
string sql = "SELECT * FROM EMP WHERE EMPNO = @Id";
var emp = connection.Query<EMP>(sql, new { Id = 7369 });
}
13
 Query
 Query Dynamic
 ExecuteScalar
 Execute
 Buffered
Dapper.NET
string sql = "SELECT * FROM EMP WHERE EMPNO = @Id";
var emp = connection.Query<EMP>(sql, new { Id = 7369 });
string sql = "SELECT * FROM EMP WHERE EMPNO = @Id";
var emp = connection.Query(sql, new { Id = 7369 });
string sql = "SELECT ENAME FROM EMP WHERE EMPNO = @Id";
var emp = connection.ExecuteScalar<string>(sql, new { Id = 7369 });
var n = connection.Execute(“DELETE FROM EMP");
var emp = connection.Query(sql, buffered: false);
14
SqlDatabaseCommand
Objets and Commandes
 Construction et destruction propres
 Optimisation des paramètres (éviter l’injection SQL) et SQL
 Conversion automatique d’objets C#
 Génération des entités C#
 Gestion des logs et traces
Méthodes d’extension de System.Data
 Transformation des propriétés C# en paramètres SQL
 DBNull
 ...
15
SqlDatabaseCommand
Exemple
using (var cmd = new SqlDatabaseCommand(CONNECTION_STRING))
{
}
cmd.CommandText.AppendLine(" SELECT * ");
cmd.CommandText.AppendLine(" FROM EMP ");
var emps = cmd.ExecuteTable<Employee>();
cmd.CommandText.AppendLine(" WHERE HIREDATE = @HireDate ");
cmd.Parameters.AddValues(new
{
HireDate = new DateTime(1980, 12, 17)
});
16
9876 NEW
SqlDatabaseCommand EMPNO ENAME
7839 KING
7698 BLAKE
7756 CLARK
...
...
7456 JONES
var emps = cmd.ExecuteTable<Employee>();
• ExecuteTable
var smith = cmd.ExecuteRow<Employee>();
• ExecuteRow
var name = cmd.ExecuteScalar<String>();
• ExecuteScalar
var n = cmd.ExecuteNonQuery();
• ExecuteQuery
17
SqlDatabaseCommand
Paramètres
cmd.CommandText.AppendLine(" SELECT ENAME ")
.AppendLine(" FROM EMP ")
.AppendLine(" WHERE EMPNO = @EmpNo ")
.AppendLine(" AND HIREDATE = @HireDate ");
cmd.Parameters.AddWithValue("@EmpNo", 7369);
cmd.Parameters.AddWithValue("@HireDate", new DateTime(1980, 12, 17));
var name = cmd.ExecuteScalar();
cmd.CommandText.AppendLine(" SELECT ENAME ")
.AppendLine(" FROM EMP ")
.AppendLine(" WHERE EMPNO = @EmpNo ")
.AppendLine(" AND HIREDATE = @HireDate ");
cmd.Parameters.AddValues(new
{
EmpNo = 7369,
HireDate = new DateTime(1980, 12, 17)
});
var name = cmd.ExecuteScalar();
18
SqlDatabaseCommand
Traces
 Logging
 Query Formatter
cmd.Log = Console.WriteLine;
cmd.Log = (message) =>
{
Console.WriteLine(message);
};
string formatted = cmd.GetCommandTextFormatted(QueryFormat.Text);
SELECT ENAME
FROM EMP
WHERE EMPNO = 7369
AND HIREDATE = '1970-05-04 14:15:16'
string formatted = cmd.GetCommandTextFormatted(QueryFormat.Html);
SELECT ENAME
FROM EMP
WHERE EMPNO = 7369
AND HIREDATE = '1970-05-04 14:15:16'
19
SqlDatabaseCommand
Générateur d’entités // *********************************************
// Code Generated with Apps72.Dev.Data.Generator
// *********************************************
using System;
namespace Data.Tests.Entities
{
/// <summary />
public partial class BONUS
{
/// <summary />
public virtual String ENAME { get; set; }
/// <summary />
public virtual String JOB { get; set; }
/// <summary />
public virtual Int32? SAL { get; set; }
/// <summary />
public virtual Int32? COMM { get; set; }
}
/// <summary />
public partial class DEPT
{
/// <summary />
public virtual Int32 DEPTNO { get; set; }
/// <summary />
public virtual String DNAME { get; set; }
/// <summary />
public virtual String LOC { get; set; }
}
var entitiesGenerator = new SqlEntitiesGenerator(CONNECTION_STRING);
foreach (var table in entitiesGenerator.Tables)
{
...
}
20
SqlDatabaseCommand
Bonnes pratiques
public class DataService : IDataService
{
public SqlDatabaseCommand GetDatabaseCommand()
{
return new SqlDatabaseCommand(CONNECTION_STRING);
}
public SqlDatabaseCommand GetDatabaseCommand(SqlTransaction trans)
{
return new SqlDatabaseCommand(trans.Connection, trans);
}
} using (var cmd = service.GetDatabaseCommand())
{
...
}
CLR Stored Procedures
22
CLR Stored Procedures
Quoi ?
 Vous pouvez écrire des procédures stockées, des déclencheurs, des types, des fonctions,
des agrégats et des fonctions d’accès aux tables, à l'aide du langage .NET Framework
Pourquoi ?
 Performances
 Outils de développement (VS, GIT, …)
 Centralisation du code
 Déploiement
23
SqlDatabaseCommand
1. Créer une bibliothèque de classe
2. Ajouter le package NuGet SqlServerClr
24
SqlDatabaseCommand
[SqlFunction(DataAccess = DataAccessKind.Read)]
public static int GetMaximumAge()
{
using (var cmd = new SqlDatabaseCommand("context connection=true"))
{
...
}
}
CREATE FUNCTION GetMaximumAge()
RETURNS INT
AS EXTERNAL NAME SampleSqlDatabaseCommandClr.SampleCLR.GetMaximumAge
25
SqlDatabaseCommand
[SqlFunction()]
public static bool IsComparableTo(string text1, string text2)
{
return text1.ComparableTo(text2) == 0;
}
SELECT dbo.IsComparableTo('Maison', 'House') -- FALSE
SELECT dbo.IsComparableTo('St Ecole', 'Saint''école&') -- TRUE
SELECT dbo.IsComparableTo('A''&é', 'aE') -- TRUE
ADO.NET
EntityFramework
SQLite
Dapper.NET
SqlDatabaseCommand
CLR Stored Procedure
Conclusion & Questions
Merci de votre participation
dvoituron@outlook.com
www.dvoituron.com
@DenisVoituron

More Related Content

PDF
What they don't tell you about JavaScript
DOCX
Fisica ii codigo
PDF
Add Some Fun to Your Functional Programming With RXJS
PDF
RxJS 5 in Depth
ODP
Daniel Sikar: Hadoop MapReduce - 06/09/2010
ODP
Aws Quick Dirty Hadoop Mapreduce Ec2 S3
KEY
W3C HTML5 KIG-How to write low garbage real-time javascript
PPTX
Data Types and Processing in ES6
What they don't tell you about JavaScript
Fisica ii codigo
Add Some Fun to Your Functional Programming With RXJS
RxJS 5 in Depth
Daniel Sikar: Hadoop MapReduce - 06/09/2010
Aws Quick Dirty Hadoop Mapreduce Ec2 S3
W3C HTML5 KIG-How to write low garbage real-time javascript
Data Types and Processing in ES6

What's hot (19)

KEY
Introduction to PiCloud
PPTX
Jk rubyslava 25
PPTX
Deleting a Node from a Binary Search Tree (Scheme
KEY
Parallel Computing in R
PPTX
Common Performance Pitfalls in Odoo apps
PPTX
Rubyslava + PyVo #48
PDF
如何「畫圖」寫測試 - RxJS Marble Test
PDF
RxJS Evolved
PDF
Python sqlite3
PDF
Tests unitaires pour PostgreSQL avec pgTap
PDF
Parallel Computing with R
PDF
RxJS - 封裝程式的藝術
PDF
Scaling up data science applications
PPT
zen and the art of SQL optimization
PPTX
RedisConf17 - Distributed Java Map Structures and Services with Redisson
PPTX
(Almost) Serverless Analytics System with BigQuery & AppEngine
DOCX
PDF
Java data structures powered by Redis. Introduction to Redisson @ Redis Light...
PDF
Unified Data Platform, by Pauline Yeung of Cisco Systems
Introduction to PiCloud
Jk rubyslava 25
Deleting a Node from a Binary Search Tree (Scheme
Parallel Computing in R
Common Performance Pitfalls in Odoo apps
Rubyslava + PyVo #48
如何「畫圖」寫測試 - RxJS Marble Test
RxJS Evolved
Python sqlite3
Tests unitaires pour PostgreSQL avec pgTap
Parallel Computing with R
RxJS - 封裝程式的藝術
Scaling up data science applications
zen and the art of SQL optimization
RedisConf17 - Distributed Java Map Structures and Services with Redisson
(Almost) Serverless Analytics System with BigQuery & AppEngine
Java data structures powered by Redis. Introduction to Redisson @ Redis Light...
Unified Data Platform, by Pauline Yeung of Cisco Systems
Ad

Similar to Développer avec un Simple Object Mapping Toolkit pour SQL Server (20)

PPTX
DevFM #20 : SqlDatabaseCommand, un Simple Object Mapping Toolkit
PPTX
ECPPM2014 - Making SimModel information available as RDF graphs
PPTX
SQL and PLSQL features for APEX Developers
PDF
Does Your IBM i Security Meet the Bar for GDPR?
PDF
NetDevOps 202: Life After Configuration
PDF
All you need to know about CREATE STATISTICS
 
PDF
Spark SQL Catalyst Code Optimization using Function Outlining with Kavana Bha...
PDF
Nyc open data project ii -- predict where to get and return my citibike
PPT
3 database-jdbc(1)
PDF
C* for Deep Learning (Andrew Jefferson, Tracktable) | Cassandra Summit 2016
PDF
RedisConf18 - Redis Memory Optimization
PPTX
Oracle Basics and Architecture
PDF
Thunderstruck
PDF
Rapid Prototyping with Solr
PDF
Oracle SQL Tuning
PDF
Scylla Summit 2016: Analytics Show Time - Spark and Presto Powered by Scylla
PDF
Gur1009
PDF
Painless Persistence in a Disconnected World
PDF
Predictive Analytics with Airflow and PySpark
PPTX
Orms vs Micro-ORMs
DevFM #20 : SqlDatabaseCommand, un Simple Object Mapping Toolkit
ECPPM2014 - Making SimModel information available as RDF graphs
SQL and PLSQL features for APEX Developers
Does Your IBM i Security Meet the Bar for GDPR?
NetDevOps 202: Life After Configuration
All you need to know about CREATE STATISTICS
 
Spark SQL Catalyst Code Optimization using Function Outlining with Kavana Bha...
Nyc open data project ii -- predict where to get and return my citibike
3 database-jdbc(1)
C* for Deep Learning (Andrew Jefferson, Tracktable) | Cassandra Summit 2016
RedisConf18 - Redis Memory Optimization
Oracle Basics and Architecture
Thunderstruck
Rapid Prototyping with Solr
Oracle SQL Tuning
Scylla Summit 2016: Analytics Show Time - Spark and Presto Powered by Scylla
Gur1009
Painless Persistence in a Disconnected World
Predictive Analytics with Airflow and PySpark
Orms vs Micro-ORMs
Ad

More from Denis Voituron (20)

PDF
Go lean, Go green
PDF
DevDay 2021 - Codez comme un ninja
PDF
Azure DevOps Tests Plan
PDF
.Net passé, présent et futur
PPTX
MIC QRS "JWT, la superstar pour sécuriser vos WebAPI"
PDF
Azure Pipelines - Et si on arrêtait de mettre en production avec des Disquettes
PDF
GitHub et Microsoft Azure DevOps - Le mariage parfait
PPTX
Azure for Dev
PPTX
DevDay 2018 - Blazor
PPTX
Les méthodes agiles dans TFS
PPTX
Awareness Oniryx - Mai 2018
PDF
A la découverte de TypeScript
PDF
Le futur de .NET
PPTX
Procédures CLR pour SQL Server : avantages et inconvénients
PPTX
Microsoft Experieces 2016 - Retour d’expériences sur TFS Online
PPTX
Les cinq bonnes pratiques des Tests Unitaires dans un projet Agile
PPTX
Présentation et bonnes pratiques du pattern MVVM - MIC Belgique
PPTX
Presentation MIC SummerCamp 2015 WaterStock
PPTX
Scrum Guide
PPTX
Visual Studio 2015: Increase your Productivity
Go lean, Go green
DevDay 2021 - Codez comme un ninja
Azure DevOps Tests Plan
.Net passé, présent et futur
MIC QRS "JWT, la superstar pour sécuriser vos WebAPI"
Azure Pipelines - Et si on arrêtait de mettre en production avec des Disquettes
GitHub et Microsoft Azure DevOps - Le mariage parfait
Azure for Dev
DevDay 2018 - Blazor
Les méthodes agiles dans TFS
Awareness Oniryx - Mai 2018
A la découverte de TypeScript
Le futur de .NET
Procédures CLR pour SQL Server : avantages et inconvénients
Microsoft Experieces 2016 - Retour d’expériences sur TFS Online
Les cinq bonnes pratiques des Tests Unitaires dans un projet Agile
Présentation et bonnes pratiques du pattern MVVM - MIC Belgique
Presentation MIC SummerCamp 2015 WaterStock
Scrum Guide
Visual Studio 2015: Increase your Productivity

Recently uploaded (20)

PDF
top salesforce developer skills in 2025.pdf
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PPTX
Computer Software and OS of computer science of grade 11.pptx
PDF
medical staffing services at VALiNTRY
PDF
Understanding Forklifts - TECH EHS Solution
PPTX
Embracing Complexity in Serverless! GOTO Serverless Bengaluru
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PDF
Navsoft: AI-Powered Business Solutions & Custom Software Development
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PDF
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PDF
System and Network Administration Chapter 2
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PPTX
CHAPTER 2 - PM Management and IT Context
PDF
Digital Strategies for Manufacturing Companies
PDF
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
top salesforce developer skills in 2025.pdf
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
Computer Software and OS of computer science of grade 11.pptx
medical staffing services at VALiNTRY
Understanding Forklifts - TECH EHS Solution
Embracing Complexity in Serverless! GOTO Serverless Bengaluru
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
Navsoft: AI-Powered Business Solutions & Custom Software Development
Odoo Companies in India – Driving Business Transformation.pdf
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
System and Network Administration Chapter 2
2025 Textile ERP Trends: SAP, Odoo & Oracle
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
CHAPTER 2 - PM Management and IT Context
Digital Strategies for Manufacturing Companies
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
Wondershare Filmora 15 Crack With Activation Key [2025

Développer avec un Simple Object Mapping Toolkit pour SQL Server

  • 1. Simple Object Mapping pour SQL Databases Développer simplement et rapidement dvoituron@outlook.com www.dvoituron.com @DenisVoituron
  • 2. 2 A propos… Denis Voituron 1995 – Ingénieur Civil 1999 – Co-fondateur d’une société spécialisée dans les CMS 2007 – Microsoft Senior Architect chez Trasys / NRB 2 @DenisVoituron dvoituron.com .be
  • 3. 3 Agenda • Background • SQL Architecture • ADO.NET • EntityFramework • Comparaison • Simple Object Mapping • Dapper.NET • SqlDatabaseCommand • SQLite • SQL Server CLR Stored Procedures 3
  • 6. SCOTT Database EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO 7839 KING PRESIDENT 17-NOV-81 5000 10 7698 BLAKE MANAGER 7839 01-MAY-81 2850 30 7756 CLARK MANAGER 7839 09-JUN-81 1500 10 ... ... ... ... 7456 JONES MANAGER 7839 02-APR-81 2975 20 DEPTNO DNAME LOC 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIOS BOSTON
  • 7. 7 ADO.NET 7 using (var connection = new SqlConnection(CONNECTION_STRING)) { connection.Open(); connection.Close(); } SELECT ENAME FROM EMP WHERE EMPNO = 7369 using (var cmd = connection.CreateCommand()) { cmd.CommandText = "SELECT ENAME " + " FROM EMP " + " WHERE EMPNO = 7369 "; } using (var adapter = new SqlDataAdapter(cmd)) { DataTable table = new DataTable(); adapter.Fill(table); string name = table.Rows[0].Field<string>("ENAME"); }
  • 8. 8 Entity Framework 8 Object Relational Mapping var db = new SCOTTEntities(); var query = from e in db.EMPs where e.EMPNO == 7369 select e; var name = query.First().DEPT.DNAME; SELECT TOP (1) [Extent1].[EMPNO] AS [EMPNO], [Extent1].[ENAME] AS [ENAME], [Extent1].[JOB] AS [JOB], [Extent1].[MGR] AS [MGR], [Extent1].[HIREDATE] AS [HIREDATE], [Extent1].[SAL] AS [SAL], [Extent1].[COMM] AS [COMM], [Extent1].[DEPTNO] AS [DEPTNO] FROM [dbo].[EMP] AS [Extent1] WHERE 7369 = [Extent1].[EMPNO] SELECT [Extent1].[DEPTNO] AS [DEPTNO], [Extent1].[DNAME] AS [DNAME], [Extent1].[LOC] AS [LOC] FROM [dbo].[DEPT] AS [Extent1] WHERE [Extent1].[DEPTNO] = @V1
  • 9. 9 ADO.NET vs Entity Framework 9 Performance Speed of Development Maintainable code (neat) Flexibility Scalability http://stackoverflow.com/questions/2698151/entity-framework-vs-linq-to-sql-vs-ado-net-with-stored-procedures
  • 12. 12 Dapper.NET Bibliothèque qui étend IDbConnection. Besoin d’une connexion déjà ouverte. using (var connection = new SqlConnection(CONNECTION_STRING)) { connection.Open(); string sql = "SELECT * FROM EMP WHERE EMPNO = @Id"; var emp = connection.Query<EMP>(sql, new { Id = 7369 }); }
  • 13. 13  Query  Query Dynamic  ExecuteScalar  Execute  Buffered Dapper.NET string sql = "SELECT * FROM EMP WHERE EMPNO = @Id"; var emp = connection.Query<EMP>(sql, new { Id = 7369 }); string sql = "SELECT * FROM EMP WHERE EMPNO = @Id"; var emp = connection.Query(sql, new { Id = 7369 }); string sql = "SELECT ENAME FROM EMP WHERE EMPNO = @Id"; var emp = connection.ExecuteScalar<string>(sql, new { Id = 7369 }); var n = connection.Execute(“DELETE FROM EMP"); var emp = connection.Query(sql, buffered: false);
  • 14. 14 SqlDatabaseCommand Objets and Commandes  Construction et destruction propres  Optimisation des paramètres (éviter l’injection SQL) et SQL  Conversion automatique d’objets C#  Génération des entités C#  Gestion des logs et traces Méthodes d’extension de System.Data  Transformation des propriétés C# en paramètres SQL  DBNull  ...
  • 15. 15 SqlDatabaseCommand Exemple using (var cmd = new SqlDatabaseCommand(CONNECTION_STRING)) { } cmd.CommandText.AppendLine(" SELECT * "); cmd.CommandText.AppendLine(" FROM EMP "); var emps = cmd.ExecuteTable<Employee>(); cmd.CommandText.AppendLine(" WHERE HIREDATE = @HireDate "); cmd.Parameters.AddValues(new { HireDate = new DateTime(1980, 12, 17) });
  • 16. 16 9876 NEW SqlDatabaseCommand EMPNO ENAME 7839 KING 7698 BLAKE 7756 CLARK ... ... 7456 JONES var emps = cmd.ExecuteTable<Employee>(); • ExecuteTable var smith = cmd.ExecuteRow<Employee>(); • ExecuteRow var name = cmd.ExecuteScalar<String>(); • ExecuteScalar var n = cmd.ExecuteNonQuery(); • ExecuteQuery
  • 17. 17 SqlDatabaseCommand Paramètres cmd.CommandText.AppendLine(" SELECT ENAME ") .AppendLine(" FROM EMP ") .AppendLine(" WHERE EMPNO = @EmpNo ") .AppendLine(" AND HIREDATE = @HireDate "); cmd.Parameters.AddWithValue("@EmpNo", 7369); cmd.Parameters.AddWithValue("@HireDate", new DateTime(1980, 12, 17)); var name = cmd.ExecuteScalar(); cmd.CommandText.AppendLine(" SELECT ENAME ") .AppendLine(" FROM EMP ") .AppendLine(" WHERE EMPNO = @EmpNo ") .AppendLine(" AND HIREDATE = @HireDate "); cmd.Parameters.AddValues(new { EmpNo = 7369, HireDate = new DateTime(1980, 12, 17) }); var name = cmd.ExecuteScalar();
  • 18. 18 SqlDatabaseCommand Traces  Logging  Query Formatter cmd.Log = Console.WriteLine; cmd.Log = (message) => { Console.WriteLine(message); }; string formatted = cmd.GetCommandTextFormatted(QueryFormat.Text); SELECT ENAME FROM EMP WHERE EMPNO = 7369 AND HIREDATE = '1970-05-04 14:15:16' string formatted = cmd.GetCommandTextFormatted(QueryFormat.Html); SELECT ENAME FROM EMP WHERE EMPNO = 7369 AND HIREDATE = '1970-05-04 14:15:16'
  • 19. 19 SqlDatabaseCommand Générateur d’entités // ********************************************* // Code Generated with Apps72.Dev.Data.Generator // ********************************************* using System; namespace Data.Tests.Entities { /// <summary /> public partial class BONUS { /// <summary /> public virtual String ENAME { get; set; } /// <summary /> public virtual String JOB { get; set; } /// <summary /> public virtual Int32? SAL { get; set; } /// <summary /> public virtual Int32? COMM { get; set; } } /// <summary /> public partial class DEPT { /// <summary /> public virtual Int32 DEPTNO { get; set; } /// <summary /> public virtual String DNAME { get; set; } /// <summary /> public virtual String LOC { get; set; } } var entitiesGenerator = new SqlEntitiesGenerator(CONNECTION_STRING); foreach (var table in entitiesGenerator.Tables) { ... }
  • 20. 20 SqlDatabaseCommand Bonnes pratiques public class DataService : IDataService { public SqlDatabaseCommand GetDatabaseCommand() { return new SqlDatabaseCommand(CONNECTION_STRING); } public SqlDatabaseCommand GetDatabaseCommand(SqlTransaction trans) { return new SqlDatabaseCommand(trans.Connection, trans); } } using (var cmd = service.GetDatabaseCommand()) { ... }
  • 22. 22 CLR Stored Procedures Quoi ?  Vous pouvez écrire des procédures stockées, des déclencheurs, des types, des fonctions, des agrégats et des fonctions d’accès aux tables, à l'aide du langage .NET Framework Pourquoi ?  Performances  Outils de développement (VS, GIT, …)  Centralisation du code  Déploiement
  • 23. 23 SqlDatabaseCommand 1. Créer une bibliothèque de classe 2. Ajouter le package NuGet SqlServerClr
  • 24. 24 SqlDatabaseCommand [SqlFunction(DataAccess = DataAccessKind.Read)] public static int GetMaximumAge() { using (var cmd = new SqlDatabaseCommand("context connection=true")) { ... } } CREATE FUNCTION GetMaximumAge() RETURNS INT AS EXTERNAL NAME SampleSqlDatabaseCommandClr.SampleCLR.GetMaximumAge
  • 25. 25 SqlDatabaseCommand [SqlFunction()] public static bool IsComparableTo(string text1, string text2) { return text1.ComparableTo(text2) == 0; } SELECT dbo.IsComparableTo('Maison', 'House') -- FALSE SELECT dbo.IsComparableTo('St Ecole', 'Saint''école&') -- TRUE SELECT dbo.IsComparableTo('A''&é', 'aE') -- TRUE
  • 27. Merci de votre participation dvoituron@outlook.com www.dvoituron.com @DenisVoituron

Editor's Notes

  • #3: NRB : Domaine de la santé, des finances, domaine public (gouvernement, ...), secteur industriel, marché mobiles, etc. 2000 collaborateurs 300 millions euros de chiffre d’affaire
  • #8: Créer un projet Console. Créer une chaine de CONNECTION_STRING = @"Server=(localdb)\ProjectsV12;Database=Scott;Integrated Security=true;“ Copier le code et l’executer. Ouvrir SQL Server Profiler et choisir le modèle TSQL... et verifier la requête SQL qui y passe. Choisir uniquement RPC:Starting et SQL:BatchStarting dans le Profiler.
  • #9: Ajouter une classe ADO.NET Entity Data Model « ScottEF » Sélectionner EF Designer from database. Choisir une chaine de connexion existante ou en créer une nouvelle vers (localdb)\ProjectsV12 et Scott Enregistrer la connection dans App.Config: ScottEntities Eventuellement, choisir Entity Framework 6.x Cocher EMP et DEPT et Pluralize object names Enregistrer le modèle sous ScottModel
  • #10: Performance : EF est médiocre, comparé aux requêtes SQL, surtout sur de grand volumes de données. Vitesse de développement : ADO trop long à écrire EF est trop complexe à comprendre et maitriser le framework. Maintenabilité du code (code propre) : ADO est trop bas niveau et est trop complexe à écrire. EF demande le développement de procédures stockées, ce qui complexifies les débuggages. Flexibilité ADO permet de construire les exactes requêtes SQL nécessaires. Pour EF, il n'est pas toujours évident de savoir ce qu'il se passe en coulisses, quelles requêtes sont effectivement exécutées sur la base de données, quelles données sont conservées en cache, dans quels cas le chargement tardif (lazy loading) s'applique, etc. Quand un bug lié à l'ORM se produit, il est parfois difficile de trouver son origine ; Evolutivité Pour ADO, les changements dans le code peuvent être nombreux. Pour EF, les évolutions dans le framework et les outils associés sont fréquents et très difficiles à maintenir dans le temps.
  • #13: 1. Créer un nouveau projet Console. 2. Ajouter le Nuget Dapper. 3. Créer une simple requête et l’exécuter. public class EMP { public Int32 EMPNO { get; set; } public String ENAME { get; set; } public String JOB { get; set; } public Int32? MGR { get; set; } public DateTime? HIREDATE { get; set; } public Decimal? SAL { get; set; } public Int32? COMM { get; set; } public Int32? DEPTNO { get; set; } }
  • #20: Ajouter un nouveau fichier Text template. Rechercher le fichier Entities.tt sur le site https://github.com/Apps72/Dev.Data Copier / coller son contenu dans le fichier Entities.tt du point 1. Vérifier que les propriétés du .tt sont Build Action = Content Custom Tool = TextTemplatingFileGenerator Enregistrer le fichier.
  • #21: Créer la classe DataService Créer un exemple d’utilisation static DataService service = new DataService(); public static void DisplaySmith() { Console.WriteLine(); Console.WriteLine("Best Practice"); using (var cmd = service.GetDatabaseCommand()) { cmd.CommandText.AppendLine(" SELECT ENAME, DNAME "); cmd.CommandText.AppendLine(" FROM EMP "); cmd.CommandText.AppendLine(" INNER JOIN DEPT ON EMP.DEPTNO = DEPT.DEPTNO "); cmd.CommandText.AppendLine(" WHERE EMPNO = @ID "); cmd.Parameters.AddValues(new { ID = 7369 }); var emp = cmd.ExecuteRow(new { EName = "", DName = "" }); Console.WriteLine($"{emp.EName} - {emp.DName}"); } } 3. Modifier le DataService pour gérer les traces et les erreurs. public SqlDatabaseCommand GetDatabaseCommand() { var cmd = new SqlDatabaseCommand(CONNECTION_STRING); cmd.Log = (message) => { Console.ForegroundColor = ConsoleColor.Gray; Console.WriteLine(message); Console.ResetColor(); }; cmd.ExceptionOccured += (sender, e) => { Console.WriteLine($"SQL ERROR: {e.Exception.Message}"); }; return cmd; }
  • #24: Créer une librairie C# en version 4.0 Ajouter le package Nuger SqlServerClr