SlideShare a Scribd company logo
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

PDF
Webinar: MongoDB Persistence with Java and Morphia
PPTX
Introduction to the new official C# Driver developed by 10gen
PDF
Web2py
PDF
Fun Teaching MongoDB New Tricks
PDF
Lab2-DB-Mongodb
PPTX
Morphia: Simplifying Persistence for Java and MongoDB
PDF
Lab1-DB-Cassandra
PDF
greenDAO
Webinar: MongoDB Persistence with Java and Morphia
Introduction to the new official C# Driver developed by 10gen
Web2py
Fun Teaching MongoDB New Tricks
Lab2-DB-Mongodb
Morphia: Simplifying Persistence for Java and MongoDB
Lab1-DB-Cassandra
greenDAO

What's hot (19)

PDF
Building node.js applications with Database Jones
PDF
Store and Process Big Data with Hadoop and Cassandra
PPTX
Sequelize
PDF
First java-server-faces-tutorial-en
PPT
Gl qtp day 3 2
PDF
Developing for Node.JS with MySQL and NoSQL
DOCX
Java assgn
PDF
Testing with Node.js
PDF
Hidden Treasures of the Python Standard Library
ODT
Mysql
PDF
Selectors and normalizing state shape
PPTX
JDBC - JPA - Spring Data
PDF
PDF
A evolução da persistência de dados (com sqlite) no android
PDF
Building android apps with kotlin
PPTX
Cassandra 2.2 & 3.0
PPT
Sqlxml vs xquery
DOCX
Custom faultpolicies
PPTX
MongoDB-SESSION03
Building node.js applications with Database Jones
Store and Process Big Data with Hadoop and Cassandra
Sequelize
First java-server-faces-tutorial-en
Gl qtp day 3 2
Developing for Node.JS with MySQL and NoSQL
Java assgn
Testing with Node.js
Hidden Treasures of the Python Standard Library
Mysql
Selectors and normalizing state shape
JDBC - JPA - Spring Data
A evolução da persistência de dados (com sqlite) no android
Building android apps with kotlin
Cassandra 2.2 & 3.0
Sqlxml vs xquery
Custom faultpolicies
MongoDB-SESSION03
Ad

Viewers also liked (20)

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

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

PDF
NoSQL and JavaScript: a Love Story
PPT
3 database-jdbc(1)
PDF
Play 2.0
PPT
Hibernate
PDF
Deeply Declarative Data Pipelines
PDF
9 Python programming notes for ktu physics and computer application semester 4
PPT
JDBC Tutorial
PPTX
Simplifying Persistence for Java and MongoDB with Morphia
PDF
Kerberizing spark. Spark Summit east
PPTX
Spring framework part 2
PDF
Dropwizard
DOCX
Java beans
PDF
Boost Development With Java EE7 On EAP7 (Demitris Andreadis)
PDF
Lecture17
PPTX
Webinar: Simplifying Persistence for Java and MongoDB
PDF
Android and the Seven Dwarfs from Devox'15
PDF
Neo4j GraphTour: Utilizing Powerful Extensions for Analytics and Operations
PPTX
Jdbc
PDF
CouchDB Mobile - From Couch to 5K in 1 Hour
PDF
The Developer Conference - CloudKit, entendendo a Cloud da Apple
NoSQL and JavaScript: a Love Story
3 database-jdbc(1)
Play 2.0
Hibernate
Deeply Declarative Data Pipelines
9 Python programming notes for ktu physics and computer application semester 4
JDBC Tutorial
Simplifying Persistence for Java and MongoDB with Morphia
Kerberizing spark. Spark Summit east
Spring framework part 2
Dropwizard
Java beans
Boost Development With Java EE7 On EAP7 (Demitris Andreadis)
Lecture17
Webinar: Simplifying Persistence for Java and MongoDB
Android and the Seven Dwarfs from Devox'15
Neo4j GraphTour: Utilizing Powerful Extensions for Analytics and Operations
Jdbc
CouchDB Mobile - From Couch to 5K in 1 Hour
The Developer Conference - CloudKit, entendendo a Cloud da Apple

Recently uploaded (20)

PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
GamePlan Trading System Review: Professional Trader's Honest Take
PDF
Advanced IT Governance
PPTX
Telecom Fraud Prevention Guide | Hyperlink InfoSystem
PDF
AI And Its Effect On The Evolving IT Sector In Australia - Elevate
PDF
Transforming Manufacturing operations through Intelligent Integrations
PDF
Advanced Soft Computing BINUS July 2025.pdf
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Empathic Computing: Creating Shared Understanding
PDF
CIFDAQ's Market Wrap: Ethereum Leads, Bitcoin Lags, Institutions Shift
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PPT
Teaching material agriculture food technology
Diabetes mellitus diagnosis method based random forest with bat algorithm
CIFDAQ's Market Insight: SEC Turns Pro Crypto
GamePlan Trading System Review: Professional Trader's Honest Take
Advanced IT Governance
Telecom Fraud Prevention Guide | Hyperlink InfoSystem
AI And Its Effect On The Evolving IT Sector In Australia - Elevate
Transforming Manufacturing operations through Intelligent Integrations
Advanced Soft Computing BINUS July 2025.pdf
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
20250228 LYD VKU AI Blended-Learning.pptx
Empathic Computing: Creating Shared Understanding
CIFDAQ's Market Wrap: Ethereum Leads, Bitcoin Lags, Institutions Shift
Per capita expenditure prediction using model stacking based on satellite ima...
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Dropbox Q2 2025 Financial Results & Investor Presentation
The Rise and Fall of 3GPP – Time for a Sabbatical?
Teaching material agriculture food technology

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