SlideShare une entreprise Scribd logo
1  sur  27
Télécharger pour lire hors ligne
1
2
Denis Voituron
Civil engineer (Mons)
Company founder
Developer: VB3, VB.Net, C#
.Net Software Architect (NRB)
Blogger
Speaker (DevApps.be)
3
• Background
• Simple Object Mapping
• SQL Server CLR Stored Procedures
4
5
6
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
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
var db = new SCOTTEntities();
var query = from e in db.EMPs
where e.EMPNO == 7369
select e.ENAME;
var name = query.First();
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].[ENAME] AS [ENAME]
FROM [dbo].[EMP] AS [Extent1]
WHERE 7369 = [Extent1].[EMPNO]
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
9http://stackoverflow.com/questions/2698151/entity-framework-vs-linq-to-sql-vs-ado-net-with-stored-procedures
Performance
Speed of Development
Maintainable code (neat)
Flexibility
Scalability
10http://blogs.msdn.com/b/adonet/archive/2012/02/14/sneak-preview-entity-framework-5-0-performance-improvements.aspx
11
12
• Library that will extend IDbConnection
• Need an opened connection
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
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
• Object and Commands
• Extension method of System.Data
15
• Sample
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
• Main methods
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
• Parameters
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
• Traces
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
• Entities Generator
// *********************************************
// 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
• Best Practice
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())
{
...
}
21
• Microsoft.Data.Sqlite
• SqliteDatabaseCommand
public SqliteDatabaseCommand GetDatabaseCommand()
{
return new SqliteDatabaseCommand("Filename=Scott.db");
}
public IEnumerable<Scott.EMP> GetAllEmployees()
{
using (var cmd = this.GetDatabaseCommand())
{
cmd.CommandText.AppendLine(" SELECT * FROM EMP ");
return cmd.ExecuteTable<Scott.EMP>();
}
}
22
23
• What?
• Why?
24
• Create a Class Library
• CLR Nuget Package
25
[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
26
[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
ADO.NET
EntityFramework
SQLite
Dapper.NET
SqlDatabaseCommand
CLR Stored Procedure
SQL Databases
Conclusion

Contenu connexe

Tendances

Linked list imp of list
Linked list imp of listLinked list imp of list
Linked list imp of listElavarasi K
 
The Ring programming language version 1.5.4 book - Part 77 of 185
The Ring programming language version 1.5.4 book - Part 77 of 185The Ring programming language version 1.5.4 book - Part 77 of 185
The Ring programming language version 1.5.4 book - Part 77 of 185Mahmoud Samir Fayed
 
2016 gunma.web games-and-asm.js
2016 gunma.web games-and-asm.js2016 gunma.web games-and-asm.js
2016 gunma.web games-and-asm.jsNoritada Shimizu
 
C++ Programming - 4th Study
C++ Programming - 4th StudyC++ Programming - 4th Study
C++ Programming - 4th StudyChris Ohk
 
C++ Programming - 14th Study
C++ Programming - 14th StudyC++ Programming - 14th Study
C++ Programming - 14th StudyChris Ohk
 
Finch.io - Purely Functional REST API with Finagle
Finch.io - Purely Functional REST API with FinagleFinch.io - Purely Functional REST API with Finagle
Finch.io - Purely Functional REST API with FinagleVladimir Kostyukov
 
Anaysing your logs with docker and elk
Anaysing your logs with docker and elkAnaysing your logs with docker and elk
Anaysing your logs with docker and elkmelvin louwerse
 
Hashing endereçamento aberto - main
Hashing endereçamento aberto - mainHashing endereçamento aberto - main
Hashing endereçamento aberto - mainElaine Cecília Gatto
 
Lewis Chiu Portfolio
Lewis Chiu PortfolioLewis Chiu Portfolio
Lewis Chiu PortfolioLewisChiu
 
C++ Programming - 2nd Study
C++ Programming - 2nd StudyC++ Programming - 2nd Study
C++ Programming - 2nd StudyChris Ohk
 
NodeUkraine - Postgresql для хипстеров или почему ваш следующий проект должен...
NodeUkraine - Postgresql для хипстеров или почему ваш следующий проект должен...NodeUkraine - Postgresql для хипстеров или почему ваш следующий проект должен...
NodeUkraine - Postgresql для хипстеров или почему ваш следующий проект должен...DmitryChirkin1
 

Tendances (20)

Linked list imp of list
Linked list imp of listLinked list imp of list
Linked list imp of list
 
Stack array
Stack arrayStack array
Stack array
 
The Ring programming language version 1.5.4 book - Part 77 of 185
The Ring programming language version 1.5.4 book - Part 77 of 185The Ring programming language version 1.5.4 book - Part 77 of 185
The Ring programming language version 1.5.4 book - Part 77 of 185
 
1
11
1
 
2016 gunma.web games-and-asm.js
2016 gunma.web games-and-asm.js2016 gunma.web games-and-asm.js
2016 gunma.web games-and-asm.js
 
C++ Programming - 4th Study
C++ Programming - 4th StudyC++ Programming - 4th Study
C++ Programming - 4th Study
 
C++ Programming - 14th Study
C++ Programming - 14th StudyC++ Programming - 14th Study
C++ Programming - 14th Study
 
20151224-games
20151224-games20151224-games
20151224-games
 
Sqlite
SqliteSqlite
Sqlite
 
Finch.io - Purely Functional REST API with Finagle
Finch.io - Purely Functional REST API with FinagleFinch.io - Purely Functional REST API with Finagle
Finch.io - Purely Functional REST API with Finagle
 
Stl algorithm-Basic types
Stl algorithm-Basic typesStl algorithm-Basic types
Stl algorithm-Basic types
 
Avl tree
Avl treeAvl tree
Avl tree
 
Anaysing your logs with docker and elk
Anaysing your logs with docker and elkAnaysing your logs with docker and elk
Anaysing your logs with docker and elk
 
Hashing endereçamento aberto - main
Hashing endereçamento aberto - mainHashing endereçamento aberto - main
Hashing endereçamento aberto - main
 
ECMAScript 5: Новое в JavaScript
ECMAScript 5: Новое в JavaScriptECMAScript 5: Новое в JavaScript
ECMAScript 5: Новое в JavaScript
 
Lewis Chiu Portfolio
Lewis Chiu PortfolioLewis Chiu Portfolio
Lewis Chiu Portfolio
 
Ns2 ns3 training in mohali
Ns2 ns3 training in mohaliNs2 ns3 training in mohali
Ns2 ns3 training in mohali
 
C++ Programming - 2nd Study
C++ Programming - 2nd StudyC++ Programming - 2nd Study
C++ Programming - 2nd Study
 
NodeUkraine - Postgresql для хипстеров или почему ваш следующий проект должен...
NodeUkraine - Postgresql для хипстеров или почему ваш следующий проект должен...NodeUkraine - Postgresql для хипстеров или почему ваш следующий проект должен...
NodeUkraine - Postgresql для хипстеров или почему ваш следующий проект должен...
 
Python sqlite3
Python sqlite3Python sqlite3
Python sqlite3
 

En vedette

Améliorer votre productivité avec Visual Studio 2012
Améliorer votre productivité avec Visual Studio 2012Améliorer votre productivité avec Visual Studio 2012
Améliorer votre productivité avec Visual Studio 2012Microsoft
 
Visual Studio Online - Outils pour la conception de logiciels - JournéeAgil...
Visual Studio Online - Outils pour la conception de logiciels - JournéeAgil...Visual Studio Online - Outils pour la conception de logiciels - JournéeAgil...
Visual Studio Online - Outils pour la conception de logiciels - JournéeAgil...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 OnlineDenis Voituron
 
Кирилл Маурин «Проектирование и разработка модульных приложений»
Кирилл Маурин «Проектирование и разработка модульных приложений» Кирилл Маурин «Проектирование и разработка модульных приложений»
Кирилл Маурин «Проектирование и разработка модульных приложений» Yulia Tsisyk
 
Илья Ефимов «IoC/DI на примере Autofac»
Илья Ефимов «IoC/DI на примере Autofac»Илья Ефимов «IoC/DI на примере Autofac»
Илья Ефимов «IoC/DI на примере Autofac»Yulia Tsisyk
 
Introduction to Team Foundation Server (TFS) Online
Introduction to Team Foundation Server (TFS) OnlineIntroduction to Team Foundation Server (TFS) Online
Introduction to Team Foundation Server (TFS) OnlineDenis Voituron
 

En vedette (7)

Améliorer votre productivité avec Visual Studio 2012
Améliorer votre productivité avec Visual Studio 2012Améliorer votre productivité avec Visual Studio 2012
Améliorer votre productivité avec Visual Studio 2012
 
Visual Studio Online - Outils pour la conception de logiciels - JournéeAgil...
Visual Studio Online - Outils pour la conception de logiciels - JournéeAgil...Visual Studio Online - Outils pour la conception de logiciels - JournéeAgil...
Visual Studio Online - Outils pour la conception de logiciels - JournéeAgil...
 
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
 
Кирилл Маурин «Проектирование и разработка модульных приложений»
Кирилл Маурин «Проектирование и разработка модульных приложений» Кирилл Маурин «Проектирование и разработка модульных приложений»
Кирилл Маурин «Проектирование и разработка модульных приложений»
 
Илья Ефимов «IoC/DI на примере Autofac»
Илья Ефимов «IoC/DI на примере Autofac»Илья Ефимов «IoC/DI на примере Autofac»
Илья Ефимов «IoC/DI на примере Autofac»
 
Introduction to Team Foundation Server (TFS) Online
Introduction to Team Foundation Server (TFS) OnlineIntroduction to Team Foundation Server (TFS) Online
Introduction to Team Foundation Server (TFS) Online
 
Scrum Guide
Scrum GuideScrum Guide
Scrum Guide
 

Similaire à DevFM #20 : SqlDatabaseCommand, un Simple Object Mapping Toolkit

Développer avec un Simple Object Mapping Toolkit pour SQL Server
Développer avec un Simple Object Mapping Toolkit pour SQL ServerDévelopper avec un Simple Object Mapping Toolkit pour SQL Server
Développer avec un Simple Object Mapping Toolkit pour SQL ServerDenis Voituron
 
Java programming lab manual
Java programming lab manualJava programming lab manual
Java programming lab manualsameer farooq
 
NetDevOps 202: Life After Configuration
NetDevOps 202: Life After ConfigurationNetDevOps 202: Life After Configuration
NetDevOps 202: Life After ConfigurationCumulus Networks
 
Ss dotnetcodexmpl
Ss dotnetcodexmplSs dotnetcodexmpl
Ss dotnetcodexmplrpravi12
 
maxbox starter72 multilanguage coding
maxbox starter72 multilanguage codingmaxbox starter72 multilanguage coding
maxbox starter72 multilanguage codingMax Kleiner
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4Abed Bukhari
 
Comparing 30 Elastic Search operations with Oracle SQL statements
Comparing 30 Elastic Search operations with Oracle SQL statementsComparing 30 Elastic Search operations with Oracle SQL statements
Comparing 30 Elastic Search operations with Oracle SQL statementsLucas Jellema
 
FINAL PROJECTpacka.docx
FINAL PROJECTpacka.docxFINAL PROJECTpacka.docx
FINAL PROJECTpacka.docxAKHIL969626
 
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 graphsPieter Pauwels
 
Create a JAVA program that performs file IO and database interaction.pdf
Create a JAVA program that performs file IO and database interaction.pdfCreate a JAVA program that performs file IO and database interaction.pdf
Create a JAVA program that performs file IO and database interaction.pdfmalavshah9013
 
PostgreSQL Procedural Languages: Tips, Tricks and Gotchas
PostgreSQL Procedural Languages: Tips, Tricks and GotchasPostgreSQL Procedural Languages: Tips, Tricks and Gotchas
PostgreSQL Procedural Languages: Tips, Tricks and GotchasJim Mlodgenski
 
A miało być tak... bez wycieków
A miało być tak... bez wyciekówA miało być tak... bez wycieków
A miało być tak... bez wyciekówKonrad Kokosa
 
Apollo ecosystem
Apollo ecosystemApollo ecosystem
Apollo ecosystemJames Akwuh
 

Similaire à DevFM #20 : SqlDatabaseCommand, un Simple Object Mapping Toolkit (20)

Développer avec un Simple Object Mapping Toolkit pour SQL Server
Développer avec un Simple Object Mapping Toolkit pour SQL ServerDévelopper avec un Simple Object Mapping Toolkit pour SQL Server
Développer avec un Simple Object Mapping Toolkit pour SQL Server
 
3 database-jdbc(1)
3 database-jdbc(1)3 database-jdbc(1)
3 database-jdbc(1)
 
Intro to Ember.JS 2016
Intro to Ember.JS 2016Intro to Ember.JS 2016
Intro to Ember.JS 2016
 
Java programming lab manual
Java programming lab manualJava programming lab manual
Java programming lab manual
 
My java file
My java fileMy java file
My java file
 
NetDevOps 202: Life After Configuration
NetDevOps 202: Life After ConfigurationNetDevOps 202: Life After Configuration
NetDevOps 202: Life After Configuration
 
Ss dotnetcodexmpl
Ss dotnetcodexmplSs dotnetcodexmpl
Ss dotnetcodexmpl
 
maxbox starter72 multilanguage coding
maxbox starter72 multilanguage codingmaxbox starter72 multilanguage coding
maxbox starter72 multilanguage coding
 
PostThis
PostThisPostThis
PostThis
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4
 
Comparing 30 Elastic Search operations with Oracle SQL statements
Comparing 30 Elastic Search operations with Oracle SQL statementsComparing 30 Elastic Search operations with Oracle SQL statements
Comparing 30 Elastic Search operations with Oracle SQL statements
 
Database security
Database securityDatabase security
Database security
 
FINAL PROJECTpacka.docx
FINAL PROJECTpacka.docxFINAL PROJECTpacka.docx
FINAL PROJECTpacka.docx
 
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
 
Create a JAVA program that performs file IO and database interaction.pdf
Create a JAVA program that performs file IO and database interaction.pdfCreate a JAVA program that performs file IO and database interaction.pdf
Create a JAVA program that performs file IO and database interaction.pdf
 
PostgreSQL Procedural Languages: Tips, Tricks and Gotchas
PostgreSQL Procedural Languages: Tips, Tricks and GotchasPostgreSQL Procedural Languages: Tips, Tricks and Gotchas
PostgreSQL Procedural Languages: Tips, Tricks and Gotchas
 
Scaling Cairngorms
Scaling CairngormsScaling Cairngorms
Scaling Cairngorms
 
A miało być tak... bez wycieków
A miało być tak... bez wyciekówA miało być tak... bez wycieków
A miało być tak... bez wycieków
 
Apollo ecosystem
Apollo ecosystemApollo ecosystem
Apollo ecosystem
 
Learning Dtrace
Learning DtraceLearning Dtrace
Learning Dtrace
 

Plus de Denis Voituron

DevDay 2021 - Codez comme un ninja
DevDay 2021 - Codez comme un ninjaDevDay 2021 - Codez comme un ninja
DevDay 2021 - Codez comme un ninjaDenis Voituron
 
Azure DevOps Tests Plan
Azure DevOps Tests PlanAzure DevOps Tests Plan
Azure DevOps Tests PlanDenis Voituron
 
.Net passé, présent et futur
.Net passé, présent et futur.Net passé, présent et futur
.Net passé, présent et futurDenis 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 DisquettesDenis 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 parfaitDenis Voituron
 
Les méthodes agiles dans TFS
Les méthodes agiles dans TFSLes méthodes agiles dans TFS
Les méthodes agiles dans TFSDenis Voituron
 
Awareness Oniryx - Mai 2018
Awareness Oniryx - Mai 2018Awareness Oniryx - Mai 2018
Awareness Oniryx - Mai 2018Denis Voituron
 
A la découverte de TypeScript
A la découverte de TypeScriptA la découverte de TypeScript
A la découverte de TypeScriptDenis 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énientsDenis 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 AgileDenis 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 BelgiqueDenis Voituron
 
Presentation MIC SummerCamp 2015 WaterStock
Presentation MIC SummerCamp 2015 WaterStockPresentation MIC SummerCamp 2015 WaterStock
Presentation MIC SummerCamp 2015 WaterStockDenis Voituron
 
Visual Studio 2015: Increase your Productivity
Visual Studio 2015: Increase your ProductivityVisual Studio 2015: Increase your Productivity
Visual Studio 2015: Increase your ProductivityDenis Voituron
 

Plus de 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
 
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
 
Visual Studio 2015: Increase your Productivity
Visual Studio 2015: Increase your ProductivityVisual Studio 2015: Increase your Productivity
Visual Studio 2015: Increase your Productivity
 
MVVM Lights
MVVM LightsMVVM Lights
MVVM Lights
 
Tfs2012 introduction
Tfs2012 introductionTfs2012 introduction
Tfs2012 introduction
 

Dernier

GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4jGraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4jNeo4j
 
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesAmazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesKrzysztofKkol1
 
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdf
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdfPros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdf
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdfkalichargn70th171
 
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...Bert Jan Schrijver
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slidesvaideheekore1
 
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...OnePlan Solutions
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldRoberto Pérez Alcolea
 
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics
 
Best Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITBest Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITmanoharjgpsolutions
 
Zer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdfZer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdfmaor17
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLionel Briand
 
The Ultimate Guide to Performance Testing in Low-Code, No-Code Environments (...
The Ultimate Guide to Performance Testing in Low-Code, No-Code Environments (...The Ultimate Guide to Performance Testing in Low-Code, No-Code Environments (...
The Ultimate Guide to Performance Testing in Low-Code, No-Code Environments (...kalichargn70th171
 
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxThe Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxRTS corp
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shardsChristopher Curtin
 
[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdf
[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdf[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdf
[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdfSteve Caron
 
Osi security architecture in network.pptx
Osi security architecture in network.pptxOsi security architecture in network.pptx
Osi security architecture in network.pptxVinzoCenzo
 
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonLeveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonApplitools
 
What’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesWhat’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesVictoriaMetrics
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorTier1 app
 
Understanding Plagiarism: Causes, Consequences and Prevention.pptx
Understanding Plagiarism: Causes, Consequences and Prevention.pptxUnderstanding Plagiarism: Causes, Consequences and Prevention.pptx
Understanding Plagiarism: Causes, Consequences and Prevention.pptxSasikiranMarri
 

Dernier (20)

GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4jGraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
 
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesAmazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
 
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdf
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdfPros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdf
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdf
 
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slides
 
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository world
 
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
 
Best Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITBest Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh IT
 
Zer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdfZer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdf
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and Repair
 
The Ultimate Guide to Performance Testing in Low-Code, No-Code Environments (...
The Ultimate Guide to Performance Testing in Low-Code, No-Code Environments (...The Ultimate Guide to Performance Testing in Low-Code, No-Code Environments (...
The Ultimate Guide to Performance Testing in Low-Code, No-Code Environments (...
 
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxThe Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards
 
[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdf
[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdf[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdf
[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdf
 
Osi security architecture in network.pptx
Osi security architecture in network.pptxOsi security architecture in network.pptx
Osi security architecture in network.pptx
 
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonLeveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
 
What’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesWhat’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 Updates
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryError
 
Understanding Plagiarism: Causes, Consequences and Prevention.pptx
Understanding Plagiarism: Causes, Consequences and Prevention.pptxUnderstanding Plagiarism: Causes, Consequences and Prevention.pptx
Understanding Plagiarism: Causes, Consequences and Prevention.pptx
 

DevFM #20 : SqlDatabaseCommand, un Simple Object Mapping Toolkit

  • 1. 1
  • 2. 2 Denis Voituron Civil engineer (Mons) Company founder Developer: VB3, VB.Net, C# .Net Software Architect (NRB) Blogger Speaker (DevApps.be)
  • 3. 3 • Background • Simple Object Mapping • SQL Server CLR Stored Procedures
  • 4. 4
  • 5. 5
  • 6. 6 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 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 var db = new SCOTTEntities(); var query = from e in db.EMPs where e.EMPNO == 7369 select e.ENAME; var name = query.First(); 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].[ENAME] AS [ENAME] FROM [dbo].[EMP] AS [Extent1] WHERE 7369 = [Extent1].[EMPNO] 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
  • 11. 11
  • 12. 12 • Library that will extend IDbConnection • Need an opened connection 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 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 • Object and Commands • Extension method of System.Data
  • 15. 15 • Sample 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 • Main methods 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 • Parameters 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 • Traces 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 • Entities Generator // ********************************************* // 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 • Best Practice 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()) { ... }
  • 21. 21 • Microsoft.Data.Sqlite • SqliteDatabaseCommand public SqliteDatabaseCommand GetDatabaseCommand() { return new SqliteDatabaseCommand("Filename=Scott.db"); } public IEnumerable<Scott.EMP> GetAllEmployees() { using (var cmd = this.GetDatabaseCommand()) { cmd.CommandText.AppendLine(" SELECT * FROM EMP "); return cmd.ExecuteTable<Scott.EMP>(); } }
  • 22. 22
  • 24. 24 • Create a Class Library • CLR Nuget Package
  • 25. 25 [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
  • 26. 26 [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

Notes de l'éditeur

  1. 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.
  2. 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
  3. 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.
  4. 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; } }
  5. 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.
  6. 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; }
  7. Créer un nouveau projet UWP (et le passer en x86). Ajouter la référence Nuget (include prerelease) SqliteDatabaseCommand Microsoft.Data.Sqlite Importer les fichiers Scott.cs DataService.cs Copier le code XAML et CodeBehind. <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> <ListView x:Name="listView" Margin="10"> <ListView.ItemTemplate> <DataTemplate> <StackPanel Orientation="Horizontal" Margin="10"> <Image Source="{Binding PICTURE}" Width="60" Height="60" /> <StackPanel Margin="20, 10"> <TextBlock Text="{Binding ENAME}" /> <TextBlock Text="{Binding JOB}" /> </StackPanel> </StackPanel> </DataTemplate> </ListView.ItemTemplate> </ListView> </Grid> public MainPage() { this.InitializeComponent(); DataService data = new DataService(); listView.ItemsSource = data.GetAllEmployees(); }
  8. Créer une librairie C# en version 4.0 Ajouter le package Nuger SqlServerClr