SlideShare a Scribd company logo
1 of 41
ASPNET CORE DATA ACCESS
ENTITY FRAMEWORK CORE & MICRO ORMS
ETAT DES LIEUX : EF CORE 1.0
 Nouvelles plateformes
 .NET CORE (ASP.NET Core, UWP)
 .NET Framework (ASP.NET, WPF, Windows Forms)
 XAMARIN
 Windows Phone
 Windows Store
 MAC
 Linux
ETAT DES LIEUX : EF CORE 1.0
 Nouvelles sources de données
 Relationnelles (SQL Server, SQL Lite, SQL Compact, Postgres, MySQL, Oracle)
 Non relationnelles (Redis, Azure Table Storage)
 InMemory (à utiliser pour les test)
 Providers disponibles uniquement pour les SGBD relationnels pour la v 1.0
 Possibilité de créer son propre provider
ENTITY FRAMEWORK CORE 1.0
 On repart de Zero mais on garde le meilleur
 Code First
 Code First from Database
 Approche totalement modulaire
 IOC friendly
 Totalement Open source comme tout ce qui finit par Core… donc code source disponible sur
GitHub et possiblité de contribuer son l’évolution.
 EF Core n’est pas production ready
ENTITY FRAMEWORK CORE 1.0
 Fonctionnalités legacy
 Change tracking
 Migrations
 DbContext API
 Linq to Entities
 SaveChanges
 Fonctionnalités supprimées
 EDMX
 Entity SQL
 Complex Mapping
 Migrations automatiques
ENTITY FRAMEWORK CORE 1.0
 Nouvelles fonctionnalités
 Dependency injection
 Lancer des Batch avec CUD
 Créer des clé étrangères
 SQL généré plus propre et plus light
 Amélioration des graphes d’objets déconnectés
 Fonctionnalités à venir
 Mapping des procédures stockées
 Lazy loading
ENTITY FRAMEWORK CORE 1.0.1
DEMARRAGE
ENTITY FRAMEWORK CORE 1.0
 Package à installer
"Microsoft.EntityFrameworkCore.SqlServer": "1.0.1 "
 Création d’un DbContext
public class CookBookContext : DbContext
{
public CookBookContext(DbContextOptions<CookBookContext> options) : base(options) { }
public DbSet<Book> Book { get; set; }
public DbSet<Recipe> Recipe { get; set; }
}
ENTITY FRAMEWORK CORE 1.0
 Config dans appsettings.json
{
"ConnectionStrings": {
"DbConnection": "Data Source=mcnltp173;Initial Catalog=CookBook;Integrated Security=True"
}
}
 Config dans Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<CookBookContext>(
options => options.UseSqlServer(Configuration.GetConnectionString("DbConnection")));
}
ENTITY FRAMEWORK CORE 1.0
 Utilisation
public class HomeController : Controller
{
private readonly CookBookContext _context;
public HomeController(CookBookContext context)
{
_context = context;
}
public IActionResult Index()
{
var books = _context.Book.ToList();
return View(books);
}
}
ENTITY FRAMEWORK CORE 1.0.1
REVERSE ENGINEERING
ENTITY FRAMEWORK CORE 1.0
 Command
dotnet ef dbcontext scaffold -c DbContextName -o ModelsFolder "MyConnectionString"
Microsoft.EntityFrameworkCore.SqlServer –force
 Config dans project.json
"dependencies": {
"Microsoft.EntityFrameworkCore.SqlServer": "1.0.1",
"Microsoft.EntityFrameworkCore.SqlServer.Design": "1.0.1",
"Microsoft.EntityFrameworkCore.Design": "1.0.0-preview2-final"
},
"tools": {
"Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final"
}
ENTITY FRAMEWORK CORE 1.0
 Code généré
public partial class CookBookContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(
@"Data Source=mcnltp173;Initial Catalog=CookBook;Integrated Security=True");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Book>(entity =>
{
entity.Property(e => e.Name)
.IsRequired()
.HasColumnType("varchar(50)");
});
}
public virtual DbSet<Book> Book { get; set; }
public virtual DbSet<Recipe> Recipe { get; set; }
}
MICRO ORMS
DAPPER - PETAPOCO - MASSIVE - SIMPLE.DATA - SERVICESTACK.ORMLITE
MICRO ORMS : DAPPER
POCO
DYNAMIC OBJECTS
MULTIPLE RESULTS
STORED PROCEDURE
TRANSACTION
ASYNC
PROVIDERS: SQLLite, SQL CE, Firebird, Oracle, MySQL, PostgreSQL and SQL Server
MICRO ORMS : DAPPER
CONFIG:
public void ConfigureServices(IServiceCollection services)
{
services.Add(new ServiceDescriptor(typeof(IConfiguration),
provider => new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json",
optional: false,
reloadOnChange: true)
.Build(),
ServiceLifetime.Singleton));
services.AddScoped<ICookBookRepository, CookBookRepository>();
}
// ou (v2) :
public static IConfigurationRoot Configuration;
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<ICookBookRepository, CookBookRepository>();
}
MICRO ORMS : DAPPER
CTOR:
private readonly IConfiguration _config;
public CookBookRepository(IConfiguration config)
{
_config = config;
}
public IDbConnection Connection
{
get
{
return new SqlConnection(_config.GetConnectionString("DbConnection"););
}
}
// ou (v2) :
public IDbConnection Connection
{
get
{
return new SqlConnection(Startup.Configuration["connectionStrings:DbConnection"]);
MICRO ORMS : DAPPER
REPO:
public IEnumerable<Book> GetAll()
{
using (IDbConnection db = Connection)
{
db.Open();
// version requete Sql
return db.Query<Book>("SELECT * FROM Book").ToList<Book>;
//return await db.QueryAsync<Book>("SELECT * FROM Book");
// version ps
//return db.Query<Book>("GetAllBooks", commandType: CommandType.StoredProcedure);
}
}
MICRO ORMS : DAPPER
public Book GetByID(int id)
{
using (IDbConnection db = Connection)
{
db.Open();
// version requete Sql
string sQuery = "SELECT * FROM Book WHERE Id = @Id";
return db.Query<Book>(sQuery, new { Id = id }).FirstOrDefault();
// version ps
//string sp = "GetBookByID";
//var parameter = new DynamicParameters();
//parameter.Add("@Id", id, dbType: DbType.Int32, direction: ParameterDirection.Input);
//return db.Query<Book>(sp, parameter, commandType: CommandType.StoredProcedure).FirstOrDefault();
}
}
MICRO ORMS : DAPPER
public Book GetMultiple(int id)
{
using (IDbConnection db = Connection)
{
db.Open();
// version requete Sql
//string query = "SELECT * FROM Book WHERE Id=@id; SELECT * FROM Recipe WHERE IdBook=@id;";
//var multipleResults = db.QueryMultiple(query, new { id = id });
// version sp
var parameter = new DynamicParameters();
parameter.Add("@id", id, dbType: DbType.Int32, direction: ParameterDirection.Input);
var multipleResults = db.QueryMultiple("GetBookRecipes", parameter,
commandType: CommandType.StoredProcedure);
var book = multipleResults.Read<Book>().SingleOrDefault();
var recipes = multipleResults.Read<Recipe>().ToList();
if (book != null && recipes != null)
book.Recipes = new List<Recipe>(); book.Recipes.AddRange(recipes);
return book;
}
MICRO ORMS : DAPPER
public void Add(Book book)
{
using (IDbConnection db = Connection)
{
db.Open();
var parameter = new DynamicParameters();
parameter.Add("@name", book.Name, dbType: DbType.String, direction: ParameterDirection.Input);
//string sQuery = "INSERT INTO Book (Name) VALUES(@Name)";
// version 1 requete Sql
//db.Execute(sQuery, parameter);
// version 2 requete Sql
//db.Execute(sQuery, book);
// version sp
db.Execute("InsertBook", parameter, commandType: CommandType.StoredProcedure);
}
}
MICRO ORMS : DAPPER
public void Update(Book book)
{
using (IDbConnection db = Connection)
{
db.Open();
var parameters = new DynamicParameters();
parameters.Add("@Id", book.Id, dbType: DbType.Int32, direction: ParameterDirection.Input);
parameters.Add("@Name", book.Name, dbType: DbType.String, direction: ParameterDirection.Input);
string sQuery = "UPDATE Book SET Name = @Name WHERE Id = @Id";
// version 1 requete Sql
//db.Execute(sQuery, parameters, commandType: CommandType.Text);
// version 2 requete Sql
//db.Execute(sQuery, book, commandType: CommandType.Text);
// version sp
db.Execute("UpdateBook", parameters, commandType: CommandType.StoredProcedure);
}
}
MICRO ORMS : DAPPER
public void Delete(int id)
{
using (IDbConnection db = Connection)
{
db.Open();
// version 1 requete Sql
//string sQuery = "DELETE FROM Book WHERE Id = @Id";
//db.Execute(sQuery, new { Id = id });
// version sp
var parameter = new DynamicParameters();
parameter.Add("@Id", id, dbType: DbType.Int32, direction: ParameterDirection.Input);
string sp = "DeleteBook";
db.Execute(sp, parameter, commandType: CommandType.StoredProcedure);
}
}
MICRO ORMS : PETAPOCO
POCO
DYNAMIC OBJECTS MAPPING
MULTIPLE RESULTS
STORED PROCEDURE
TRANSACTION
ASYNC
T4
PROVIDERS: SQL Server, SQL Server CE, MS Access, SQLite, MySQL, MariaDB, PostgreSQL, Firebird DB, and Oracle
APP.CONFIG
MICRO ORMS : PETAPOCO
CONFIG:
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<ICookBookRepository, CookBookRepository>();
}
CTOR:
private readonly Database _db;
public CookBookRepository()
{
var connectionString = ConfigurationManager.ConnectionStrings["DbConnection"].ConnectionString;
_db = new Database(connectionString, new SqlServerDatabaseProvider());
}
MICRO ORMS : PETAPOCO
REPO:
public IEnumerable<Book> GetAll()
{
using (IDatabase dbConnection = Connection)
{
return _db.Query<Book>("SELECT * FROM Book");
}
}
public Book GetByID(int id)
{
using (IDatabase dbConnection = Connection)
{
return _db.FirstOrDefault<Book>($"SELECT * FROM Book WHERE Id={id}");
}
}
MICRO ORMS : PETAPOCO
public void Add(Book book)
{
using (IDatabase dbConnection = Connection)
{
_db.Insert(book);
}
}
public void Update(Book book)
{
using (IDatabase dbConnection = Connection)
{
_db.Update(book);
}
}
public void Delete(Book book)
{
using (IDatabase dbConnection = Connection)
{
_db.Delete(book);
}
}
MICRO ORMS : MASSIVE
DYNAMIC OBJECTS
MULTIPLE RESULTS
STORED PROCEDURE
TRANSACTION
ASYNC
PROVIDERS: SQL Server, Oracle, SQLite, PostgreSQL
APP.CONFIG
MICRO ORMS : MASSIVE
CONFIG:
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<ICookBookRepository, CookBookRepository>();
}
public class Book : DynamicModel
{
public Book():base("DbConnection", "Book","Id") { }
public int Id { get; set; }
public string Name { get; set; }
}
MICRO ORMS : MASSIVE
REPO:
public async Task<IList<dynamic>> GetAll()
{
return await table.AllAsync();
}
public async Task<dynamic> GetByID(int id)
{
return await table.SingleAsync($"WHERE Id={id}");
}
MICRO ORMS : MASSIVE
public async Task Add(dynamic book)
{
await table.InsertAsync(book);
}
public async Task Update(dynamic book)
{
await table.UpdateAsync(book, book.Id);
}
public async Task Delete(int id)
{
await table.DeleteAsync(id);
}
MICRO ORMS : SIMPLE.DATA
POCO
DYNAMIC OBJECTS
MULTIPLE RESULTS
STORED PROCEDURE
TRANSACTION
ASYNC
PROVIDERS: SQL Server, SQL Azure, SQL Server Compact, Oracle, MySQL, SQLite, PostgreSQL, SQLAnywhere, Informix,
MongoDB, OData
MICRO ORMS : SIMPLE.DATA
CONFIG:
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
Configuration = builder.Build();
}
public static IConfigurationRoot Configuration;
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<ICookBookRepository, CookBookRepository>()
}
CTOR:
private readonly dynamic _db;
public CookBookRepository()
{
_db = Database.OpenConnection(Startup.Configuration["connectionStrings:DbConnection"]);
}
MICRO ORMS : SIMPLE.DATA
REPO:
public async Task<List<Book>> GetAll()
{
return await _db.Book.All().ToList<Book>();
//return await _db["Book"].All().ToList<Book>();
}
public async Task<Book> GetByID(int id)
{
return await _db.Book.Find(_db.Book.Id == id);
//return await _db.Book.Get(id).Cast<Book>();
}
MICRO ORMS : SIMPLE.DATA
public async Task Add(Book book)
{
await _db.Book.Insert(book);
}
public async Task Update(Book book)
{
await _db.Book.UpdateById(Id: book.Id, Name: book.Name);
}
public async Task Delete(int id)
{
await _db.Book.DeleteById(id);
}
MICRO ORMS : SERVICESTACK.ORMLITE
POCO
DYNAMIC OBJECTS
MULTIPLE RESULTS
STORED PROCEDURE
TRANSACTION
ASYNC
PROVIDERS: SqlServer, PostgreSQL, MySql, Sqlite.Mono, Sqlite.Windows, Oracle, Firebird, VistaDb,
AWS RDS (PostgreSQL, Aurora, MySQL, MariaDB, SQL Server)
MICRO ORMS : SERVICESTACK.ORMLITE
CONFIG:
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<ICookBookRepository, CookBookRepository>();
}
CTOR:
private readonly IDbConnectionFactory _dbFactory;
public CookBookRepository()
{
_dbFactory = new OrmLiteConnectionFactory(
Startup.Configuration["connectionStrings:DbConnection"],
SqlServer2012Dialect.Provider);
}
MICRO ORM : SERVICESTACK.ORMLITE
REPO:
public IEnumerable<Book> GetAll()
{
using (IDbConnection dbConnection = _dbFactory.OpenDbConnection())
{
return dbConnection.Select<Book>();
//return await dbConnection.SelectAsync<Book>();
}
}
public Book GetByID(int id)
{
using (IDbConnection dbConnection = _dbFactory.OpenDbConnection())
{
return dbConnection.Select<Book>(s => s.Id == id).FirstOrDefault();
//return await dbConnection.SelectAsync<Book>(s => s.Id == id).FirstOrDefault();
}
}
MICRO ORMS : SERVICESTACK.ORMLITE
public void Add(Book book)
{
using (IDbConnection dbConnection = _dbFactory.OpenDbConnection())
{
dbConnection.Insert<Book>(book);
// await dbConnection.InsertAsync<Book>(book);
}
}
public void Delete(int id)
{
using (IDbConnection dbConnection = _dbFactory.OpenDbConnection())
{
dbConnection.Delete<Book>(s => s.Id == id);
// await dbConnection.DeleteAsync<Book>(s => s.Id == id);
}
}
MICRO ORMS : SERVICESTACK.ORMLITE
public void Update(Book book)
{
using (IDbConnection dbConnection = _dbFactory.OpenDbConnection())
{
// dbConnection.Update<Book>(
// dbConnection.UpdateAdd<Book>(
// dbConnection.UpdateAll<Book>(
// await dbConnection.UpdateOnlyAsync<Book>(
dbConnection.UpdateOnly<Book>(
book,
onlyFields: f => f.Name == book.Name,
where: s => s.Id == book.Id
);
}
}
LINKS
 PETAPOCO
 http://www.toptensoftware.com/petapoco/
 https://github.com/CollaboratingPlatypus/PetaPoco
 MASSIVE OK
 https://github.com/FransBouma/Massive
 ORMLITE OK
 https://github.com/ServiceStack/ServiceStack.OrmLite
 http://gistlyn.com/?collection=991db51e44674ad01d3d318b24cf0934&gist=a62b1e7a8da57c7d1fda95b3da5303eb
 SIMPLEDATA OK
 https://github.com/markrendle/Simple.Data
 DAPPER OK
 https://github.com/StackExchange/dapper-dot-net

More Related Content

What's hot

Building node.js applications with Database Jones
Building node.js applications with Database JonesBuilding node.js applications with Database Jones
Building node.js applications with Database JonesJohn David Duncan
 
Store and Process Big Data with Hadoop and Cassandra
Store and Process Big Data with Hadoop and CassandraStore and Process Big Data with Hadoop and Cassandra
Store and Process Big Data with Hadoop and CassandraDeependra Ariyadewa
 
First java-server-faces-tutorial-en
First java-server-faces-tutorial-enFirst java-server-faces-tutorial-en
First java-server-faces-tutorial-entechbed
 
Developing for Node.JS with MySQL and NoSQL
Developing for Node.JS with MySQL and NoSQLDeveloping for Node.JS with MySQL and NoSQL
Developing for Node.JS with MySQL and NoSQLJohn David Duncan
 
Java assgn
Java assgnJava assgn
Java assgnaa11bb11
 
Hidden Treasures of the Python Standard Library
Hidden Treasures of the Python Standard LibraryHidden Treasures of the Python Standard Library
Hidden Treasures of the Python Standard Librarydoughellmann
 
Selectors and normalizing state shape
Selectors and normalizing state shapeSelectors and normalizing state shape
Selectors and normalizing state shapeMuntasir Chowdhury
 
JDBC - JPA - Spring Data
JDBC - JPA - Spring DataJDBC - JPA - Spring Data
JDBC - JPA - Spring DataArturs Drozdovs
 
A evolução da persistência de dados (com sqlite) no android
A evolução da persistência de dados (com sqlite) no androidA evolução da persistência de dados (com sqlite) no android
A evolução da persistência de dados (com sqlite) no androidRodrigo de Souza Castro
 
Building android apps with kotlin
Building android apps with kotlinBuilding android apps with kotlin
Building android apps with kotlinShem Magnezi
 
Sqlxml vs xquery
Sqlxml vs xquerySqlxml vs xquery
Sqlxml vs xqueryAmol Pujari
 

What's hot (19)

Building node.js applications with Database Jones
Building node.js applications with Database JonesBuilding node.js applications with Database Jones
Building node.js applications with Database Jones
 
Store and Process Big Data with Hadoop and Cassandra
Store and Process Big Data with Hadoop and CassandraStore and Process Big Data with Hadoop and Cassandra
Store and Process Big Data with Hadoop and Cassandra
 
Sequelize
SequelizeSequelize
Sequelize
 
First java-server-faces-tutorial-en
First java-server-faces-tutorial-enFirst java-server-faces-tutorial-en
First java-server-faces-tutorial-en
 
Gl qtp day 3 2
Gl qtp day 3   2Gl qtp day 3   2
Gl qtp day 3 2
 
Developing for Node.JS with MySQL and NoSQL
Developing for Node.JS with MySQL and NoSQLDeveloping for Node.JS with MySQL and NoSQL
Developing for Node.JS with MySQL and NoSQL
 
Java assgn
Java assgnJava assgn
Java assgn
 
Testing with Node.js
Testing with Node.jsTesting with Node.js
Testing with Node.js
 
Hidden Treasures of the Python Standard Library
Hidden Treasures of the Python Standard LibraryHidden Treasures of the Python Standard Library
Hidden Treasures of the Python Standard Library
 
Mysql
MysqlMysql
Mysql
 
Selectors and normalizing state shape
Selectors and normalizing state shapeSelectors and normalizing state shape
Selectors and normalizing state shape
 
JDBC - JPA - Spring Data
JDBC - JPA - Spring DataJDBC - JPA - Spring Data
JDBC - JPA - Spring Data
 
Hadoop
HadoopHadoop
Hadoop
 
A evolução da persistência de dados (com sqlite) no android
A evolução da persistência de dados (com sqlite) no androidA evolução da persistência de dados (com sqlite) no android
A evolução da persistência de dados (com sqlite) no android
 
Building android apps with kotlin
Building android apps with kotlinBuilding android apps with kotlin
Building android apps with kotlin
 
Cassandra 2.2 & 3.0
Cassandra 2.2 & 3.0Cassandra 2.2 & 3.0
Cassandra 2.2 & 3.0
 
Sqlxml vs xquery
Sqlxml vs xquerySqlxml vs xquery
Sqlxml vs xquery
 
Custom faultpolicies
Custom faultpoliciesCustom faultpolicies
Custom faultpolicies
 
MongoDB-SESSION03
MongoDB-SESSION03MongoDB-SESSION03
MongoDB-SESSION03
 

Viewers also liked

Feedback Loops...to infinity, and beyond!
Feedback Loops...to infinity, and beyond!Feedback Loops...to infinity, and beyond!
Feedback Loops...to infinity, and beyond!Rui Carvalho
 
Рекламные услуги Business Family
Рекламные услуги Business FamilyРекламные услуги Business Family
Рекламные услуги Business FamilyBusiness Family
 
Resumes and cover_letters
Resumes and cover_lettersResumes and cover_letters
Resumes and cover_lettersJhonelle Babz
 
booklet 4 mac 2012
booklet 4 mac 2012booklet 4 mac 2012
booklet 4 mac 2012Hanan Bolous
 
Thinks - Monday
Thinks - MondayThinks - Monday
Thinks - Mondayjwickberg
 
Enterprise Node - Code Quality
Enterprise Node - Code QualityEnterprise Node - Code Quality
Enterprise Node - Code QualityKurtis Kemple
 
Cultura del agua en Frailes I: conoce tus fuentes y Acuíferos
Cultura del agua en Frailes I: conoce tus fuentes y AcuíferosCultura del agua en Frailes I: conoce tus fuentes y Acuíferos
Cultura del agua en Frailes I: conoce tus fuentes y AcuíferosTúRInnova @tecnico_turismo
 
Рекламные услуги Business Family
Рекламные услуги Business FamilyРекламные услуги Business Family
Рекламные услуги Business FamilyBusiness Family
 
Интернет маркетинг по новым технологиям
Интернет маркетинг по новым технологиямИнтернет маркетинг по новым технологиям
Интернет маркетинг по новым технологиямBusiness Family
 
Taleem(education)
Taleem(education)Taleem(education)
Taleem(education)AnsibRaza
 
Quien quiere ser millonario emili
Quien quiere ser millonario emiliQuien quiere ser millonario emili
Quien quiere ser millonario emiliMaryory Gomez
 
hubungan tingkat pendidikan orangtua dengan prestasi hasil belajar anak
hubungan tingkat pendidikan orangtua dengan prestasi hasil belajar anakhubungan tingkat pendidikan orangtua dengan prestasi hasil belajar anak
hubungan tingkat pendidikan orangtua dengan prestasi hasil belajar anakSiti Nurjanah
 
Enterprise Node - Code Discoverability
Enterprise Node - Code DiscoverabilityEnterprise Node - Code Discoverability
Enterprise Node - Code DiscoverabilityKurtis Kemple
 
Kombinacni logicka funkce
Kombinacni logicka funkceKombinacni logicka funkce
Kombinacni logicka funkcePetr Chládek
 
Social Media in the Library, Phnom Penh October 2013
Social Media in the Library, Phnom Penh October 2013Social Media in the Library, Phnom Penh October 2013
Social Media in the Library, Phnom Penh October 2013LottaRWI
 
Маркетинговые инструменты в продвижении услуг на рынке строительства и недвиж...
Маркетинговые инструменты в продвижении услуг на рынке строительства и недвиж...Маркетинговые инструменты в продвижении услуг на рынке строительства и недвиж...
Маркетинговые инструменты в продвижении услуг на рынке строительства и недвиж...Business Family
 

Viewers also liked (20)

Feedback Loops...to infinity, and beyond!
Feedback Loops...to infinity, and beyond!Feedback Loops...to infinity, and beyond!
Feedback Loops...to infinity, and beyond!
 
Рекламные услуги Business Family
Рекламные услуги Business FamilyРекламные услуги Business Family
Рекламные услуги Business Family
 
Peta
PetaPeta
Peta
 
Resumes and cover_letters
Resumes and cover_lettersResumes and cover_letters
Resumes and cover_letters
 
booklet 4 mac 2012
booklet 4 mac 2012booklet 4 mac 2012
booklet 4 mac 2012
 
путешествие к настоящему (4)
путешествие к настоящему (4)путешествие к настоящему (4)
путешествие к настоящему (4)
 
Thinks - Monday
Thinks - MondayThinks - Monday
Thinks - Monday
 
Enterprise Node - Code Quality
Enterprise Node - Code QualityEnterprise Node - Code Quality
Enterprise Node - Code Quality
 
Cultura del agua en Frailes I: conoce tus fuentes y Acuíferos
Cultura del agua en Frailes I: conoce tus fuentes y AcuíferosCultura del agua en Frailes I: conoce tus fuentes y Acuíferos
Cultura del agua en Frailes I: conoce tus fuentes y Acuíferos
 
You have to want it.
You have to want it.You have to want it.
You have to want it.
 
Рекламные услуги Business Family
Рекламные услуги Business FamilyРекламные услуги Business Family
Рекламные услуги Business Family
 
Интернет маркетинг по новым технологиям
Интернет маркетинг по новым технологиямИнтернет маркетинг по новым технологиям
Интернет маркетинг по новым технологиям
 
Taleem(education)
Taleem(education)Taleem(education)
Taleem(education)
 
Ev90
Ev90Ev90
Ev90
 
Quien quiere ser millonario emili
Quien quiere ser millonario emiliQuien quiere ser millonario emili
Quien quiere ser millonario emili
 
hubungan tingkat pendidikan orangtua dengan prestasi hasil belajar anak
hubungan tingkat pendidikan orangtua dengan prestasi hasil belajar anakhubungan tingkat pendidikan orangtua dengan prestasi hasil belajar anak
hubungan tingkat pendidikan orangtua dengan prestasi hasil belajar anak
 
Enterprise Node - Code Discoverability
Enterprise Node - Code DiscoverabilityEnterprise Node - Code Discoverability
Enterprise Node - Code Discoverability
 
Kombinacni logicka funkce
Kombinacni logicka funkceKombinacni logicka funkce
Kombinacni logicka funkce
 
Social Media in the Library, Phnom Penh October 2013
Social Media in the Library, Phnom Penh October 2013Social Media in the Library, Phnom Penh October 2013
Social Media in the Library, Phnom Penh October 2013
 
Маркетинговые инструменты в продвижении услуг на рынке строительства и недвиж...
Маркетинговые инструменты в продвижении услуг на рынке строительства и недвиж...Маркетинговые инструменты в продвижении услуг на рынке строительства и недвиж...
Маркетинговые инструменты в продвижении услуг на рынке строительства и недвиж...
 

Similar to Entity Framework Core & Micro-Orms with Asp.Net Core

NoSQL and JavaScript: a Love Story
NoSQL and JavaScript: a Love StoryNoSQL and JavaScript: a Love Story
NoSQL and JavaScript: a Love StoryAlexandre Morgaut
 
Hibernate
Hibernate Hibernate
Hibernate Sunil OS
 
Deeply Declarative Data Pipelines
Deeply Declarative Data PipelinesDeeply Declarative Data Pipelines
Deeply Declarative Data PipelinesHostedbyConfluent
 
Simplifying Persistence for Java and MongoDB with Morphia
Simplifying Persistence for Java and MongoDB with MorphiaSimplifying Persistence for Java and MongoDB with Morphia
Simplifying Persistence for Java and MongoDB with MorphiaMongoDB
 
Kerberizing spark. Spark Summit east
Kerberizing spark. Spark Summit eastKerberizing spark. Spark Summit east
Kerberizing spark. Spark Summit eastJorge Lopez-Malla
 
Spring framework part 2
Spring framework part 2Spring framework part 2
Spring framework part 2Haroon Idrees
 
Boost Development With Java EE7 On EAP7 (Demitris Andreadis)
Boost Development With Java EE7 On EAP7 (Demitris Andreadis)Boost Development With Java EE7 On EAP7 (Demitris Andreadis)
Boost Development With Java EE7 On EAP7 (Demitris Andreadis)Red Hat Developers
 
Webinar: Simplifying Persistence for Java and MongoDB
Webinar: Simplifying Persistence for Java and MongoDBWebinar: Simplifying Persistence for Java and MongoDB
Webinar: Simplifying Persistence for Java and MongoDBMongoDB
 
Android and the Seven Dwarfs from Devox'15
Android and the Seven Dwarfs from Devox'15Android and the Seven Dwarfs from Devox'15
Android and the Seven Dwarfs from Devox'15Murat Yener
 
Neo4j GraphTour: Utilizing Powerful Extensions for Analytics and Operations
Neo4j GraphTour: Utilizing Powerful Extensions for Analytics and OperationsNeo4j GraphTour: Utilizing Powerful Extensions for Analytics and Operations
Neo4j GraphTour: Utilizing Powerful Extensions for Analytics and OperationsMark Needham
 
CouchDB Mobile - From Couch to 5K in 1 Hour
CouchDB Mobile - From Couch to 5K in 1 HourCouchDB Mobile - From Couch to 5K in 1 Hour
CouchDB Mobile - From Couch to 5K in 1 HourPeter Friese
 
The Developer Conference - CloudKit, entendendo a Cloud da Apple
The Developer Conference - CloudKit, entendendo a Cloud da AppleThe Developer Conference - CloudKit, entendendo a Cloud da Apple
The Developer Conference - CloudKit, entendendo a Cloud da AppleRodrigo Leite
 

Similar to Entity Framework Core & Micro-Orms with Asp.Net Core (20)

NoSQL and JavaScript: a Love Story
NoSQL and JavaScript: a Love StoryNoSQL and JavaScript: a Love Story
NoSQL and JavaScript: a Love Story
 
3 database-jdbc(1)
3 database-jdbc(1)3 database-jdbc(1)
3 database-jdbc(1)
 
Play 2.0
Play 2.0Play 2.0
Play 2.0
 
Hibernate
Hibernate Hibernate
Hibernate
 
Deeply Declarative Data Pipelines
Deeply Declarative Data PipelinesDeeply Declarative Data Pipelines
Deeply Declarative Data Pipelines
 
JDBC Tutorial
JDBC TutorialJDBC Tutorial
JDBC Tutorial
 
Simplifying Persistence for Java and MongoDB with Morphia
Simplifying Persistence for Java and MongoDB with MorphiaSimplifying Persistence for Java and MongoDB with Morphia
Simplifying Persistence for Java and MongoDB with Morphia
 
Kerberizing spark. Spark Summit east
Kerberizing spark. Spark Summit eastKerberizing spark. Spark Summit east
Kerberizing spark. Spark Summit east
 
Spring framework part 2
Spring framework part 2Spring framework part 2
Spring framework part 2
 
Dropwizard
DropwizardDropwizard
Dropwizard
 
Java beans
Java beansJava beans
Java beans
 
Boost Development With Java EE7 On EAP7 (Demitris Andreadis)
Boost Development With Java EE7 On EAP7 (Demitris Andreadis)Boost Development With Java EE7 On EAP7 (Demitris Andreadis)
Boost Development With Java EE7 On EAP7 (Demitris Andreadis)
 
Lecture17
Lecture17Lecture17
Lecture17
 
Webinar: Simplifying Persistence for Java and MongoDB
Webinar: Simplifying Persistence for Java and MongoDBWebinar: Simplifying Persistence for Java and MongoDB
Webinar: Simplifying Persistence for Java and MongoDB
 
Android and the Seven Dwarfs from Devox'15
Android and the Seven Dwarfs from Devox'15Android and the Seven Dwarfs from Devox'15
Android and the Seven Dwarfs from Devox'15
 
Neo4j GraphTour: Utilizing Powerful Extensions for Analytics and Operations
Neo4j GraphTour: Utilizing Powerful Extensions for Analytics and OperationsNeo4j GraphTour: Utilizing Powerful Extensions for Analytics and Operations
Neo4j GraphTour: Utilizing Powerful Extensions for Analytics and Operations
 
Jdbc
JdbcJdbc
Jdbc
 
CouchDB Mobile - From Couch to 5K in 1 Hour
CouchDB Mobile - From Couch to 5K in 1 HourCouchDB Mobile - From Couch to 5K in 1 Hour
CouchDB Mobile - From Couch to 5K in 1 Hour
 
The Developer Conference - CloudKit, entendendo a Cloud da Apple
The Developer Conference - CloudKit, entendendo a Cloud da AppleThe Developer Conference - CloudKit, entendendo a Cloud da Apple
The Developer Conference - CloudKit, entendendo a Cloud da Apple
 
spring-tutorial
spring-tutorialspring-tutorial
spring-tutorial
 

Recently uploaded

Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 

Recently uploaded (20)

Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 

Entity Framework Core & Micro-Orms with Asp.Net Core

  • 1. ASPNET CORE DATA ACCESS ENTITY FRAMEWORK CORE & MICRO ORMS
  • 2. ETAT DES LIEUX : EF CORE 1.0  Nouvelles plateformes  .NET CORE (ASP.NET Core, UWP)  .NET Framework (ASP.NET, WPF, Windows Forms)  XAMARIN  Windows Phone  Windows Store  MAC  Linux
  • 3. ETAT DES LIEUX : EF CORE 1.0  Nouvelles sources de données  Relationnelles (SQL Server, SQL Lite, SQL Compact, Postgres, MySQL, Oracle)  Non relationnelles (Redis, Azure Table Storage)  InMemory (à utiliser pour les test)  Providers disponibles uniquement pour les SGBD relationnels pour la v 1.0  Possibilité de créer son propre provider
  • 4. ENTITY FRAMEWORK CORE 1.0  On repart de Zero mais on garde le meilleur  Code First  Code First from Database  Approche totalement modulaire  IOC friendly  Totalement Open source comme tout ce qui finit par Core… donc code source disponible sur GitHub et possiblité de contribuer son l’évolution.  EF Core n’est pas production ready
  • 5. ENTITY FRAMEWORK CORE 1.0  Fonctionnalités legacy  Change tracking  Migrations  DbContext API  Linq to Entities  SaveChanges  Fonctionnalités supprimées  EDMX  Entity SQL  Complex Mapping  Migrations automatiques
  • 6. ENTITY FRAMEWORK CORE 1.0  Nouvelles fonctionnalités  Dependency injection  Lancer des Batch avec CUD  Créer des clé étrangères  SQL généré plus propre et plus light  Amélioration des graphes d’objets déconnectés  Fonctionnalités à venir  Mapping des procédures stockées  Lazy loading
  • 7. ENTITY FRAMEWORK CORE 1.0.1 DEMARRAGE
  • 8. ENTITY FRAMEWORK CORE 1.0  Package à installer "Microsoft.EntityFrameworkCore.SqlServer": "1.0.1 "  Création d’un DbContext public class CookBookContext : DbContext { public CookBookContext(DbContextOptions<CookBookContext> options) : base(options) { } public DbSet<Book> Book { get; set; } public DbSet<Recipe> Recipe { get; set; } }
  • 9. ENTITY FRAMEWORK CORE 1.0  Config dans appsettings.json { "ConnectionStrings": { "DbConnection": "Data Source=mcnltp173;Initial Catalog=CookBook;Integrated Security=True" } }  Config dans Startup.cs public void ConfigureServices(IServiceCollection services) { services.AddDbContext<CookBookContext>( options => options.UseSqlServer(Configuration.GetConnectionString("DbConnection"))); }
  • 10. ENTITY FRAMEWORK CORE 1.0  Utilisation public class HomeController : Controller { private readonly CookBookContext _context; public HomeController(CookBookContext context) { _context = context; } public IActionResult Index() { var books = _context.Book.ToList(); return View(books); } }
  • 11. ENTITY FRAMEWORK CORE 1.0.1 REVERSE ENGINEERING
  • 12. ENTITY FRAMEWORK CORE 1.0  Command dotnet ef dbcontext scaffold -c DbContextName -o ModelsFolder "MyConnectionString" Microsoft.EntityFrameworkCore.SqlServer –force  Config dans project.json "dependencies": { "Microsoft.EntityFrameworkCore.SqlServer": "1.0.1", "Microsoft.EntityFrameworkCore.SqlServer.Design": "1.0.1", "Microsoft.EntityFrameworkCore.Design": "1.0.0-preview2-final" }, "tools": { "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final" }
  • 13. ENTITY FRAMEWORK CORE 1.0  Code généré public partial class CookBookContext : DbContext { protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer( @"Data Source=mcnltp173;Initial Catalog=CookBook;Integrated Security=True"); } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Book>(entity => { entity.Property(e => e.Name) .IsRequired() .HasColumnType("varchar(50)"); }); } public virtual DbSet<Book> Book { get; set; } public virtual DbSet<Recipe> Recipe { get; set; } }
  • 14. MICRO ORMS DAPPER - PETAPOCO - MASSIVE - SIMPLE.DATA - SERVICESTACK.ORMLITE
  • 15. MICRO ORMS : DAPPER POCO DYNAMIC OBJECTS MULTIPLE RESULTS STORED PROCEDURE TRANSACTION ASYNC PROVIDERS: SQLLite, SQL CE, Firebird, Oracle, MySQL, PostgreSQL and SQL Server
  • 16. MICRO ORMS : DAPPER CONFIG: public void ConfigureServices(IServiceCollection services) { services.Add(new ServiceDescriptor(typeof(IConfiguration), provider => new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .Build(), ServiceLifetime.Singleton)); services.AddScoped<ICookBookRepository, CookBookRepository>(); } // ou (v2) : public static IConfigurationRoot Configuration; public void ConfigureServices(IServiceCollection services) { services.AddScoped<ICookBookRepository, CookBookRepository>(); }
  • 17. MICRO ORMS : DAPPER CTOR: private readonly IConfiguration _config; public CookBookRepository(IConfiguration config) { _config = config; } public IDbConnection Connection { get { return new SqlConnection(_config.GetConnectionString("DbConnection");); } } // ou (v2) : public IDbConnection Connection { get { return new SqlConnection(Startup.Configuration["connectionStrings:DbConnection"]);
  • 18. MICRO ORMS : DAPPER REPO: public IEnumerable<Book> GetAll() { using (IDbConnection db = Connection) { db.Open(); // version requete Sql return db.Query<Book>("SELECT * FROM Book").ToList<Book>; //return await db.QueryAsync<Book>("SELECT * FROM Book"); // version ps //return db.Query<Book>("GetAllBooks", commandType: CommandType.StoredProcedure); } }
  • 19. MICRO ORMS : DAPPER public Book GetByID(int id) { using (IDbConnection db = Connection) { db.Open(); // version requete Sql string sQuery = "SELECT * FROM Book WHERE Id = @Id"; return db.Query<Book>(sQuery, new { Id = id }).FirstOrDefault(); // version ps //string sp = "GetBookByID"; //var parameter = new DynamicParameters(); //parameter.Add("@Id", id, dbType: DbType.Int32, direction: ParameterDirection.Input); //return db.Query<Book>(sp, parameter, commandType: CommandType.StoredProcedure).FirstOrDefault(); } }
  • 20. MICRO ORMS : DAPPER public Book GetMultiple(int id) { using (IDbConnection db = Connection) { db.Open(); // version requete Sql //string query = "SELECT * FROM Book WHERE Id=@id; SELECT * FROM Recipe WHERE IdBook=@id;"; //var multipleResults = db.QueryMultiple(query, new { id = id }); // version sp var parameter = new DynamicParameters(); parameter.Add("@id", id, dbType: DbType.Int32, direction: ParameterDirection.Input); var multipleResults = db.QueryMultiple("GetBookRecipes", parameter, commandType: CommandType.StoredProcedure); var book = multipleResults.Read<Book>().SingleOrDefault(); var recipes = multipleResults.Read<Recipe>().ToList(); if (book != null && recipes != null) book.Recipes = new List<Recipe>(); book.Recipes.AddRange(recipes); return book; }
  • 21. MICRO ORMS : DAPPER public void Add(Book book) { using (IDbConnection db = Connection) { db.Open(); var parameter = new DynamicParameters(); parameter.Add("@name", book.Name, dbType: DbType.String, direction: ParameterDirection.Input); //string sQuery = "INSERT INTO Book (Name) VALUES(@Name)"; // version 1 requete Sql //db.Execute(sQuery, parameter); // version 2 requete Sql //db.Execute(sQuery, book); // version sp db.Execute("InsertBook", parameter, commandType: CommandType.StoredProcedure); } }
  • 22. MICRO ORMS : DAPPER public void Update(Book book) { using (IDbConnection db = Connection) { db.Open(); var parameters = new DynamicParameters(); parameters.Add("@Id", book.Id, dbType: DbType.Int32, direction: ParameterDirection.Input); parameters.Add("@Name", book.Name, dbType: DbType.String, direction: ParameterDirection.Input); string sQuery = "UPDATE Book SET Name = @Name WHERE Id = @Id"; // version 1 requete Sql //db.Execute(sQuery, parameters, commandType: CommandType.Text); // version 2 requete Sql //db.Execute(sQuery, book, commandType: CommandType.Text); // version sp db.Execute("UpdateBook", parameters, commandType: CommandType.StoredProcedure); } }
  • 23. MICRO ORMS : DAPPER public void Delete(int id) { using (IDbConnection db = Connection) { db.Open(); // version 1 requete Sql //string sQuery = "DELETE FROM Book WHERE Id = @Id"; //db.Execute(sQuery, new { Id = id }); // version sp var parameter = new DynamicParameters(); parameter.Add("@Id", id, dbType: DbType.Int32, direction: ParameterDirection.Input); string sp = "DeleteBook"; db.Execute(sp, parameter, commandType: CommandType.StoredProcedure); } }
  • 24. MICRO ORMS : PETAPOCO POCO DYNAMIC OBJECTS MAPPING MULTIPLE RESULTS STORED PROCEDURE TRANSACTION ASYNC T4 PROVIDERS: SQL Server, SQL Server CE, MS Access, SQLite, MySQL, MariaDB, PostgreSQL, Firebird DB, and Oracle APP.CONFIG
  • 25. MICRO ORMS : PETAPOCO CONFIG: public void ConfigureServices(IServiceCollection services) { services.AddScoped<ICookBookRepository, CookBookRepository>(); } CTOR: private readonly Database _db; public CookBookRepository() { var connectionString = ConfigurationManager.ConnectionStrings["DbConnection"].ConnectionString; _db = new Database(connectionString, new SqlServerDatabaseProvider()); }
  • 26. MICRO ORMS : PETAPOCO REPO: public IEnumerable<Book> GetAll() { using (IDatabase dbConnection = Connection) { return _db.Query<Book>("SELECT * FROM Book"); } } public Book GetByID(int id) { using (IDatabase dbConnection = Connection) { return _db.FirstOrDefault<Book>($"SELECT * FROM Book WHERE Id={id}"); } }
  • 27. MICRO ORMS : PETAPOCO public void Add(Book book) { using (IDatabase dbConnection = Connection) { _db.Insert(book); } } public void Update(Book book) { using (IDatabase dbConnection = Connection) { _db.Update(book); } } public void Delete(Book book) { using (IDatabase dbConnection = Connection) { _db.Delete(book); } }
  • 28. MICRO ORMS : MASSIVE DYNAMIC OBJECTS MULTIPLE RESULTS STORED PROCEDURE TRANSACTION ASYNC PROVIDERS: SQL Server, Oracle, SQLite, PostgreSQL APP.CONFIG
  • 29. MICRO ORMS : MASSIVE CONFIG: public void ConfigureServices(IServiceCollection services) { services.AddScoped<ICookBookRepository, CookBookRepository>(); } public class Book : DynamicModel { public Book():base("DbConnection", "Book","Id") { } public int Id { get; set; } public string Name { get; set; } }
  • 30. MICRO ORMS : MASSIVE REPO: public async Task<IList<dynamic>> GetAll() { return await table.AllAsync(); } public async Task<dynamic> GetByID(int id) { return await table.SingleAsync($"WHERE Id={id}"); }
  • 31. MICRO ORMS : MASSIVE public async Task Add(dynamic book) { await table.InsertAsync(book); } public async Task Update(dynamic book) { await table.UpdateAsync(book, book.Id); } public async Task Delete(int id) { await table.DeleteAsync(id); }
  • 32. MICRO ORMS : SIMPLE.DATA POCO DYNAMIC OBJECTS MULTIPLE RESULTS STORED PROCEDURE TRANSACTION ASYNC PROVIDERS: SQL Server, SQL Azure, SQL Server Compact, Oracle, MySQL, SQLite, PostgreSQL, SQLAnywhere, Informix, MongoDB, OData
  • 33. MICRO ORMS : SIMPLE.DATA CONFIG: public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true); Configuration = builder.Build(); } public static IConfigurationRoot Configuration; public void ConfigureServices(IServiceCollection services) { services.AddScoped<ICookBookRepository, CookBookRepository>() } CTOR: private readonly dynamic _db; public CookBookRepository() { _db = Database.OpenConnection(Startup.Configuration["connectionStrings:DbConnection"]); }
  • 34. MICRO ORMS : SIMPLE.DATA REPO: public async Task<List<Book>> GetAll() { return await _db.Book.All().ToList<Book>(); //return await _db["Book"].All().ToList<Book>(); } public async Task<Book> GetByID(int id) { return await _db.Book.Find(_db.Book.Id == id); //return await _db.Book.Get(id).Cast<Book>(); }
  • 35. MICRO ORMS : SIMPLE.DATA public async Task Add(Book book) { await _db.Book.Insert(book); } public async Task Update(Book book) { await _db.Book.UpdateById(Id: book.Id, Name: book.Name); } public async Task Delete(int id) { await _db.Book.DeleteById(id); }
  • 36. MICRO ORMS : SERVICESTACK.ORMLITE POCO DYNAMIC OBJECTS MULTIPLE RESULTS STORED PROCEDURE TRANSACTION ASYNC PROVIDERS: SqlServer, PostgreSQL, MySql, Sqlite.Mono, Sqlite.Windows, Oracle, Firebird, VistaDb, AWS RDS (PostgreSQL, Aurora, MySQL, MariaDB, SQL Server)
  • 37. MICRO ORMS : SERVICESTACK.ORMLITE CONFIG: public void ConfigureServices(IServiceCollection services) { services.AddScoped<ICookBookRepository, CookBookRepository>(); } CTOR: private readonly IDbConnectionFactory _dbFactory; public CookBookRepository() { _dbFactory = new OrmLiteConnectionFactory( Startup.Configuration["connectionStrings:DbConnection"], SqlServer2012Dialect.Provider); }
  • 38. MICRO ORM : SERVICESTACK.ORMLITE REPO: public IEnumerable<Book> GetAll() { using (IDbConnection dbConnection = _dbFactory.OpenDbConnection()) { return dbConnection.Select<Book>(); //return await dbConnection.SelectAsync<Book>(); } } public Book GetByID(int id) { using (IDbConnection dbConnection = _dbFactory.OpenDbConnection()) { return dbConnection.Select<Book>(s => s.Id == id).FirstOrDefault(); //return await dbConnection.SelectAsync<Book>(s => s.Id == id).FirstOrDefault(); } }
  • 39. MICRO ORMS : SERVICESTACK.ORMLITE public void Add(Book book) { using (IDbConnection dbConnection = _dbFactory.OpenDbConnection()) { dbConnection.Insert<Book>(book); // await dbConnection.InsertAsync<Book>(book); } } public void Delete(int id) { using (IDbConnection dbConnection = _dbFactory.OpenDbConnection()) { dbConnection.Delete<Book>(s => s.Id == id); // await dbConnection.DeleteAsync<Book>(s => s.Id == id); } }
  • 40. MICRO ORMS : SERVICESTACK.ORMLITE public void Update(Book book) { using (IDbConnection dbConnection = _dbFactory.OpenDbConnection()) { // dbConnection.Update<Book>( // dbConnection.UpdateAdd<Book>( // dbConnection.UpdateAll<Book>( // await dbConnection.UpdateOnlyAsync<Book>( dbConnection.UpdateOnly<Book>( book, onlyFields: f => f.Name == book.Name, where: s => s.Id == book.Id ); } }
  • 41. LINKS  PETAPOCO  http://www.toptensoftware.com/petapoco/  https://github.com/CollaboratingPlatypus/PetaPoco  MASSIVE OK  https://github.com/FransBouma/Massive  ORMLITE OK  https://github.com/ServiceStack/ServiceStack.OrmLite  http://gistlyn.com/?collection=991db51e44674ad01d3d318b24cf0934&gist=a62b1e7a8da57c7d1fda95b3da5303eb  SIMPLEDATA OK  https://github.com/markrendle/Simple.Data  DAPPER OK  https://github.com/StackExchange/dapper-dot-net