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

What's hot

Introduction to PiCloud
Introduction to PiCloudIntroduction to PiCloud
Introduction to PiCloud
Bill Koch
 
Deleting a Node from a Binary Search Tree (Scheme
Deleting a Node from a Binary Search Tree (SchemeDeleting a Node from a Binary Search Tree (Scheme
Deleting a Node from a Binary Search Tree (Scheme
adcaine
 
Parallel Computing in R
Parallel Computing in RParallel Computing in R
Parallel Computing in R
mickey24
 
Common Performance Pitfalls in Odoo apps
Common Performance Pitfalls in Odoo appsCommon Performance Pitfalls in Odoo apps
Common Performance Pitfalls in Odoo apps
Odoo
 
Rubyslava + PyVo #48
Rubyslava + PyVo #48Rubyslava + PyVo #48
Rubyslava + PyVo #48
Jozef Képesi
 
如何「畫圖」寫測試 - RxJS Marble Test
如何「畫圖」寫測試 - RxJS Marble Test如何「畫圖」寫測試 - RxJS Marble Test
如何「畫圖」寫測試 - RxJS Marble Test
名辰 洪
 
RxJS Evolved
RxJS EvolvedRxJS Evolved
RxJS Evolved
trxcllnt
 
Python sqlite3
Python sqlite3Python sqlite3
Python sqlite3
Alexey Bovanenko
 
Tests unitaires pour PostgreSQL avec pgTap
Tests unitaires pour PostgreSQL avec pgTapTests unitaires pour PostgreSQL avec pgTap
Tests unitaires pour PostgreSQL avec pgTap
Rodolphe Quiédeville
 
Parallel Computing with R
Parallel Computing with RParallel Computing with R
Parallel Computing with R
Peter Solymos
 
RxJS - 封裝程式的藝術
RxJS - 封裝程式的藝術RxJS - 封裝程式的藝術
RxJS - 封裝程式的藝術
名辰 洪
 
Scaling up data science applications
Scaling up data science applicationsScaling up data science applications
Scaling up data science applications
Kexin Xie
 
zen and the art of SQL optimization
zen and the art of SQL optimizationzen and the art of SQL optimization
zen and the art of SQL optimization
Karen Morton
 
RedisConf17 - Distributed Java Map Structures and Services with Redisson
RedisConf17 - Distributed Java Map Structures and Services with RedissonRedisConf17 - Distributed Java Map Structures and Services with Redisson
RedisConf17 - Distributed Java Map Structures and Services with Redisson
Redis Labs
 
(Almost) Serverless Analytics System with BigQuery & AppEngine
(Almost) Serverless Analytics System with BigQuery & AppEngine(Almost) Serverless Analytics System with BigQuery & AppEngine
(Almost) Serverless Analytics System with BigQuery & AppEngine
Gabriel PREDA
 
Java data structures powered by Redis. Introduction to Redisson @ Redis Light...
Java data structures powered by Redis. Introduction to Redisson @ Redis Light...Java data structures powered by Redis. Introduction to Redisson @ Redis Light...
Java data structures powered by Redis. Introduction to Redisson @ Redis Light...
Nikita Koksharov
 
Unified Data Platform, by Pauline Yeung of Cisco Systems
Unified Data Platform, by Pauline Yeung of Cisco SystemsUnified Data Platform, by Pauline Yeung of Cisco Systems
Unified Data Platform, by Pauline Yeung of Cisco Systems
Altinity Ltd
 

What's hot (19)

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

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

DevFM #20 : SqlDatabaseCommand, un Simple Object Mapping Toolkit
DevFM #20 : SqlDatabaseCommand, un Simple Object Mapping ToolkitDevFM #20 : SqlDatabaseCommand, un Simple Object Mapping Toolkit
DevFM #20 : SqlDatabaseCommand, un Simple Object Mapping Toolkit
Denis Voituron
 
ECPPM2014 - Making SimModel information available as RDF graphs
ECPPM2014 - Making SimModel information available as RDF graphsECPPM2014 - Making SimModel information available as RDF graphs
ECPPM2014 - Making SimModel information available as RDF graphs
Pieter Pauwels
 
SQL and PLSQL features for APEX Developers
SQL and PLSQL features for APEX DevelopersSQL and PLSQL features for APEX Developers
SQL and PLSQL features for APEX Developers
Connor McDonald
 
Does Your IBM i Security Meet the Bar for GDPR?
Does Your IBM i Security Meet the Bar for GDPR?Does Your IBM i Security Meet the Bar for GDPR?
Does Your IBM i Security Meet the Bar for GDPR?
Precisely
 
NetDevOps 202: Life After Configuration
NetDevOps 202: Life After ConfigurationNetDevOps 202: Life After Configuration
NetDevOps 202: Life After Configuration
Cumulus Networks
 
All you need to know about CREATE STATISTICS
All you need to know about CREATE STATISTICSAll you need to know about CREATE STATISTICS
All you need to know about CREATE STATISTICS
EDB
 
Spark SQL Catalyst Code Optimization using Function Outlining with Kavana Bha...
Spark SQL Catalyst Code Optimization using Function Outlining with Kavana Bha...Spark SQL Catalyst Code Optimization using Function Outlining with Kavana Bha...
Spark SQL Catalyst Code Optimization using Function Outlining with Kavana Bha...
Databricks
 
Nyc open data project ii -- predict where to get and return my citibike
Nyc open data project ii -- predict where to get and return my citibikeNyc open data project ii -- predict where to get and return my citibike
Nyc open data project ii -- predict where to get and return my citibike
Vivian S. Zhang
 
3 database-jdbc(1)
3 database-jdbc(1)3 database-jdbc(1)
3 database-jdbc(1)
hameedkhan2017
 
C* for Deep Learning (Andrew Jefferson, Tracktable) | Cassandra Summit 2016
C* for Deep Learning (Andrew Jefferson, Tracktable) | Cassandra Summit 2016C* for Deep Learning (Andrew Jefferson, Tracktable) | Cassandra Summit 2016
C* for Deep Learning (Andrew Jefferson, Tracktable) | Cassandra Summit 2016
DataStax
 
RedisConf18 - Redis Memory Optimization
RedisConf18 - Redis Memory OptimizationRedisConf18 - Redis Memory Optimization
RedisConf18 - Redis Memory Optimization
Redis Labs
 
Oracle Basics and Architecture
Oracle Basics and ArchitectureOracle Basics and Architecture
Oracle Basics and ArchitectureSidney Chen
 
Thunderstruck
ThunderstruckThunderstruck
Thunderstruck
wagnerandrade
 
Rapid Prototyping with Solr
Rapid Prototyping with SolrRapid Prototyping with Solr
Rapid Prototyping with Solr
Erik Hatcher
 
Oracle SQL Tuning
Oracle SQL TuningOracle SQL Tuning
Oracle SQL Tuning
Alex Zaballa
 
Scylla Summit 2016: Analytics Show Time - Spark and Presto Powered by Scylla
Scylla Summit 2016: Analytics Show Time - Spark and Presto Powered by ScyllaScylla Summit 2016: Analytics Show Time - Spark and Presto Powered by Scylla
Scylla Summit 2016: Analytics Show Time - Spark and Presto Powered by Scylla
ScyllaDB
 
Painless Persistence in a Disconnected World
Painless Persistence in a Disconnected WorldPainless Persistence in a Disconnected World
Painless Persistence in a Disconnected World
Christian Melchior
 
Predictive Analytics with Airflow and PySpark
Predictive Analytics with Airflow and PySparkPredictive Analytics with Airflow and PySpark
Predictive Analytics with Airflow and PySpark
Russell Jurney
 
Orms vs Micro-ORMs
Orms vs Micro-ORMsOrms vs Micro-ORMs
Orms vs Micro-ORMs
David Paquette
 

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

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

More from Denis Voituron

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

More from Denis Voituron (20)

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

Recently uploaded

APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)
Boni García
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Globus
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
Neo4j
 
Pro Unity Game Development with C-sharp Book
Pro Unity Game Development with C-sharp BookPro Unity Game Development with C-sharp Book
Pro Unity Game Development with C-sharp Book
abdulrafaychaudhry
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Crescat
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
timtebeek1
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
Globus
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
Adele Miller
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
takuyayamamoto1800
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
Shane Coughlan
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
Ortus Solutions, Corp
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
Google
 

Recently uploaded (20)

APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
 
Pro Unity Game Development with C-sharp Book
Pro Unity Game Development with C-sharp BookPro Unity Game Development with C-sharp Book
Pro Unity Game Development with C-sharp Book
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
 

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

  1. NRB : Domaine de la santé, des finances, domaine public (gouvernement, ...), secteur industriel, marché mobiles, etc. 2000 collaborateurs 300 millions euros de chiffre d’affaire
  2. 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.
  3. 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
  4. 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.
  5. 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; } }
  6. 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.
  7. 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; }
  8. Créer une librairie C# en version 4.0 Ajouter le package Nuger SqlServerClr