SlideShare a Scribd company logo
ORM Technologies and
Entity Framework (EF)
Entity Framework, DbContext, CRUD
Operations, Code First, Migrations
Svetlin Nakov
Inspiration Manager
Software University
http://softuni.bg
Table of Contents
1. ORM Technologies – Basic Concepts
2. Entity Framework – Overview
3. Database First with EF
4. Reading Data and CRUD operations with EF
5. Code First with EF
 Domain Classes and DbContext
6. Migrations in EF
2
Introduction to ORM Technologies
What is Object-Relational Mapping (ORM)?
4
 Object-Relational Mapping (ORM) is a programming technique
for automatic mapping data and database schema
 Map relational DB tables to classes and objects
 ORM creates a "virtual object database"
 Used from the programming language (C#, Java, PHP, …)
 ORM frameworks automate the ORM process
 A.k.a. Object-Relational Persistence Frameworks
ORM Technologies
5
ORM Mapping – Example
ORM
Framework
Relational
database
schema
ORM
Entities
(C# classes)
Entity Framework (EF)
The ORM Framework for .NET
7
 Entity Framework (EF) is the standard ORM framework for .NET
 Maps relational database to C# object model
 Powerful data manipulation API over the mapped schema
 CRUD operations and complex querying with LINQ
 Database first approach: from database to C# classes
 Code first approach: from classes to DB schema
 Visual Studio generates EF data models
 Data mappings consist of C# classes, attributes and XML
Overview of EF
8
EF: Basic Workflow
2. Write & execute
query over
IQueryable
3. EF generates &
executes an SQL
query in the DB
1. Define the data
model (use a DB
visual designer
or code first)
9
EF: Basic Workflow (2)
5. Modify data
with C# code
and call "Save
Changes"
6. Entity Framework
generates &
executes SQL
command to
modify the DB
4. EF transforms
the query
results into
.NET objects
10
 Install Entity Framework through the NuGet package manager
Installing Entity Framework
Database First with Entity
Framework and Visual Studio
Live Demo
Entity Framework – Components
 The DbContext class
 DbContext holds the DB connection
 Holds and DbSet<T> for the entity classes
 Provides LINQ-based data access ( through IQueryable)
 Provides API for CRUD operations
 Entity classes
 Hold entities (objects with their attributes and relations)
 Each database table is typically mapped to a single C# entity class
12
13
 We can also use extension methods for constructing the query
 Find element by id
Reading Data with LINQ Query
using (var context = new SoftUniEntities())
{
var project = context.Projects.Find(2);
Console.WriteLine(project.Name);
}
using (var context = new SoftUniEntities())
{
var employees = context.Employees
.Select(c => c.FirstName)
.Where(c => c.JobTitle == "Design Engineering")
.ToList();
}
This is called projection
ToList() method
executes the SQL query
This is called
selection
14
 To create a new database row use the method Add(…) of the
corresponding collection:
 SaveChanges() method executes the SQL insert / update /
delete commands in the database
Creating New Data
var project = new Project()
{
Name = "Judge System",
StartDate = new DateTime(2015, 4, 15)
};
context.Projects.Add(order);
context.SaveChanges(); This will execute an SQL INSERT
Create a new
project object
Mark the object for inserting
15
 We can also add cascading entities to the database:
 This way we don't have to add Project individually
 They will be added when the Employee entity (employee) is
inserted to the database
Cascading Inserts
Employee employee = new Employee();
employee.FirstName = "Petya";
employee.LastName = "Grozdarska";
employee.Projects.Add(new Project { Name = "SoftUni Conf" } );
softUniEntities.Employees.Add(employee);
softUniEntities.SaveChanges();
16
 DbContext allows modifying entity properties and persisting
them in the database
 Just load an entity, modify it and call SaveChanges()
 The DbContext automatically tracks all changes made on its
entity objects
Updating Existing Data
Employees employee =
softUniEntities.Employees.First();
employees.FirstName = "Alex";
context.SaveChanges(); This will execute
an SQL UPDATE
This will execute an
SQL SELECT to load
the first order
17
 Delete is done by Remove() on the specified entity collection
 SaveChanges() method performs the delete action in the
database
Deleting Existing Data
Employees employee =
softUniEntities.Employees.First();
softUniEntities.Employees.Remove(employee);
softUniEntities.SaveChanges();
Mark the entity for
deleting at the next save
This will execute the
SQL DELETE command
18
Native SQL Queries
var context = new SoftUniEntities();
string nativeSQLQuery =
"SELECT FirstName + ' ' + LastName " +
"FROM dbo.Employees WHERE JobTitle = {0}";
var employees = context.Database.SqlQuery<string>(
nativeSQLQuery, "Marketing Specialist");
foreach (var emp in employees)
{
Console.WriteLine(emp);
}
Parameter
placeholder
Parameter
value
Return
type
CRUD Operations with EF
Live Demo
"Code First" Approach in EF
From Classes to DB Schema
21
 Create database schema and generate C# code (models) from it
Database First in EF
DB
EDMX
Model
Domain
Classes
Code First in EF
Custom
Configuration
DbContext &
ModelBuilder
Domain
classes
As needed
DB
22
Domain Classes (Models)
 Bunch of normal C# classes (POCO)
 May hold navigation properties
public class PostAnswer
{
public int Id { get; set; }
public string Content { get; set; }
public int PostId { get; set; }
public virtual Post Post { get; set; }
}
Primary key
Foreign key
Navigation property
Virtual for lazy loading
23
24
 Another example of domain class (model)
Domain Classes (Models) (2)
public class Post
{
public Post()
{
this.Answers = new HashSet<PostAnswer>();
}
public virtual ICollection<PostAnswer> Answers { get; set; }
public PostType Type { get; set; }
}
This prevents
NullReferenceException
Navigation
property
Enumeration
25
Defining the DbContext Class
using System.Data.Entity;
using CodeFirst.Models;
public class ForumDbContext : DbContext
{
public DbSet<Category> Categories { get; set; }
public DbSet<Post> Posts { get; set; }
public DbSet<PostAnswer> PostAnswers { get; set; }
public DbSet<Tag> Tags { get; set; }
}
Put all entity
classes as DbSets
CRUD Operations with EF Code First
var db = new ForumDbContext();
var category = new Category { Name = "Database course" };
db.Categories.Add(category);
var post = new Post();
post.Title = "Homework Deadline";
post.Content = "Please extend the homework deadline";
post.Type = PostType.Normal;
post.Category = category;
post.Tags.Add(new Tag { Text = "homework" });
post.Tags.Add(new Tag { Text = "deadline" });
db.Posts.Add(post);
db.SaveChanges();
26
"Code First" Approach in EF
Live Demo
Using Code First Migrations in EF
29
 Enable Code First Migrations
 Open Package Manager Console
 Run Enable-Migrations command
 -EnableAutomaticMigrations for auto migrations
Code First Migrations in Entity Framework
30
Configuring the Migration Strategy
// Enable automatic DB migrations for ForumDbContext
Database.SetInitializer(
new MigrateDatabaseToLatestVersion<
ForumDbContext, DbMigrationConfig>());
class DbMigrationConfig :
DbMigrationsConfiguration<ForumDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = true;
}
}
Using Code First Migrations in EF
Live Demo
?
https://softuni.bg
ORM Technologies and Entity Framework (EF)
Free Trainings @ Software University
 Software University Foundation – softuni.org
 Software University – High-Quality Education,
Profession and Job for Software Developers
 softuni.bg
 Software University @ Facebook
 facebook.com/SoftwareUniversity
 Software University @ YouTube
 youtube.com/SoftwareUniversity
 Software University Forums – forum.softuni.bg

More Related Content

What's hot (20)

PPTX
Spring data jpa
Jeevesh Pandey
 
PPTX
Entity Framework Overview
Eric Nelson
 
PPTX
Entity framework code first
Confiz
 
PDF
Introduction to JPA and Hibernate including examples
ecosio GmbH
 
PPTX
Database Programming Techniques
Raji Ghawi
 
PPTX
Introduction to Hibernate Framework
Raveendra R
 
PDF
Data access
Joshua Yoon
 
PDF
Hibernate An Introduction
Nguyen Cao
 
PPT
Jdbc
smvdurajesh
 
PPT
Hibernate presentation
Manav Prasad
 
PPTX
Hibernate ppt
Aneega
 
PPTX
Introduction to JPA Framework
Collaboration Technologies
 
PPT
Introduction to Hibernate
Krishnakanth Goud
 
PDF
Java Programming - 08 java threading
Danairat Thanabodithammachari
 
PPT
hibernate with JPA
Mohammad Faizan
 
PPTX
Hibernate in Nutshell
Onkar Deshpande
 
PPTX
Spring (1)
Aneega
 
DOC
Advanced core java
Rajeev Uppala
 
PDF
C# Advanced L07-Design Patterns
Mohammad Shaker
 
PPT
jpa-hibernate-presentation
John Slick
 
Spring data jpa
Jeevesh Pandey
 
Entity Framework Overview
Eric Nelson
 
Entity framework code first
Confiz
 
Introduction to JPA and Hibernate including examples
ecosio GmbH
 
Database Programming Techniques
Raji Ghawi
 
Introduction to Hibernate Framework
Raveendra R
 
Data access
Joshua Yoon
 
Hibernate An Introduction
Nguyen Cao
 
Hibernate presentation
Manav Prasad
 
Hibernate ppt
Aneega
 
Introduction to JPA Framework
Collaboration Technologies
 
Introduction to Hibernate
Krishnakanth Goud
 
Java Programming - 08 java threading
Danairat Thanabodithammachari
 
hibernate with JPA
Mohammad Faizan
 
Hibernate in Nutshell
Onkar Deshpande
 
Spring (1)
Aneega
 
Advanced core java
Rajeev Uppala
 
C# Advanced L07-Design Patterns
Mohammad Shaker
 
jpa-hibernate-presentation
John Slick
 

Viewers also liked (20)

PDF
Regular Expressions: QA Challenge Accepted Conf (March 2015)
Svetlin Nakov
 
ODP
Why not ORM
Michal Špaček
 
PPTX
05 entity framework
glubox
 
PDF
SUE AGILE MVVM (Italian)
Sabino Labarile
 
PPTX
Slide typescript - xe dotnet - Codemotion Rome 2015
Codemotion
 
PPTX
System.AddIn @ Xe.Net
Mauro Servienti
 
PPTX
Nakov at Fuck Up Nights - July 2015 @ Sofia
Svetlin Nakov
 
PPTX
Следвай вдъхновението си! (фестивал "Свободата да бъдеш - април 2016")
Svetlin Nakov
 
PDF
Slide Prelaurea. Alessandro Andreosè
guesta10af3
 
PPTX
Introduzione a MVVM e Caliburn.Micro
Massimo Bonanni
 
PPTX
Професия "програмист"
Svetlin Nakov
 
PPTX
Dependency Injection and Inversion Of Control
Simone Busoli
 
PDF
ORM: Object-relational mapping
Abhilash M A
 
PPTX
Inversion of Control @ CD2008
Mauro Servienti
 
PDF
Как да станем софтуерни инженери и да стартираме ИТ бизнес?
Svetlin Nakov
 
PPTX
Model-View-ViewModel
DotNetMarche
 
PPTX
Работа с Естествен Интелект – Личност – Време – 3 юли 2013 @ НЛП клуб
Svetlin Nakov
 
PDF
Architetttura Della Soluzione
Luca Milan
 
PPTX
UI Composition
DotNetMarche
 
PPTX
Dependency Injection
Raffaele Fanizzi
 
Regular Expressions: QA Challenge Accepted Conf (March 2015)
Svetlin Nakov
 
Why not ORM
Michal Špaček
 
05 entity framework
glubox
 
SUE AGILE MVVM (Italian)
Sabino Labarile
 
Slide typescript - xe dotnet - Codemotion Rome 2015
Codemotion
 
System.AddIn @ Xe.Net
Mauro Servienti
 
Nakov at Fuck Up Nights - July 2015 @ Sofia
Svetlin Nakov
 
Следвай вдъхновението си! (фестивал "Свободата да бъдеш - април 2016")
Svetlin Nakov
 
Slide Prelaurea. Alessandro Andreosè
guesta10af3
 
Introduzione a MVVM e Caliburn.Micro
Massimo Bonanni
 
Професия "програмист"
Svetlin Nakov
 
Dependency Injection and Inversion Of Control
Simone Busoli
 
ORM: Object-relational mapping
Abhilash M A
 
Inversion of Control @ CD2008
Mauro Servienti
 
Как да станем софтуерни инженери и да стартираме ИТ бизнес?
Svetlin Nakov
 
Model-View-ViewModel
DotNetMarche
 
Работа с Естествен Интелект – Личност – Време – 3 юли 2013 @ НЛП клуб
Svetlin Nakov
 
Architetttura Della Soluzione
Luca Milan
 
UI Composition
DotNetMarche
 
Dependency Injection
Raffaele Fanizzi
 

Similar to Entity Framework: Nakov @ BFU Hackhaton 2015 (20)

PDF
Learn Entity Framework in a day with Code First, Model First and Database First
Jibran Rasheed Khan
 
DOCX
Getting Started with Entity Framework in .NET
StudySection
 
DOCX
Learning MVC Part 3 Creating MVC Application with EntityFramework
Akhil Mittal
 
PPTX
dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...
dotNet Miami
 
PPTX
Microsoft Entity Framework
Mahmoud Tolba
 
PPTX
Applying EF Code First at Your Job
Enea Gabriel
 
PPTX
Entity framework
Mehdi jannati
 
PPTX
Overview of entity framework by software outsourcing company india
Jignesh Aakoliya
 
PPTX
MVC and Entity Framework 4
James Johnson
 
PDF
Intake 38 data access 5
Mahmoud Ouf
 
PDF
Intake 37 ef2
Mahmoud Ouf
 
PPTX
ASP.NET MVC and Entity Framework 4
James Johnson
 
PPTX
Entity Framework
vrluckyin
 
PPT
Entity frameworks101
Rich Helton
 
PDF
Entity Framework Interview Questions PDF By ScholarHat
Scholarhat
 
PPTX
La sql
James Johnson
 
PDF
Entity Framework 6 Recipes 2nd Edition Brian Driscoll
raffygobahc9
 
PDF
[FREE PDF sample] Programming Entity Framework DbContext 1st Edition Julia Le...
pontyrincoe
 
PPTX
Entity Framework Today (May 2012)
Julie Lerman
 
PPTX
Entity Framework v1 and v2
Eric Nelson
 
Learn Entity Framework in a day with Code First, Model First and Database First
Jibran Rasheed Khan
 
Getting Started with Entity Framework in .NET
StudySection
 
Learning MVC Part 3 Creating MVC Application with EntityFramework
Akhil Mittal
 
dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...
dotNet Miami
 
Microsoft Entity Framework
Mahmoud Tolba
 
Applying EF Code First at Your Job
Enea Gabriel
 
Entity framework
Mehdi jannati
 
Overview of entity framework by software outsourcing company india
Jignesh Aakoliya
 
MVC and Entity Framework 4
James Johnson
 
Intake 38 data access 5
Mahmoud Ouf
 
Intake 37 ef2
Mahmoud Ouf
 
ASP.NET MVC and Entity Framework 4
James Johnson
 
Entity Framework
vrluckyin
 
Entity frameworks101
Rich Helton
 
Entity Framework Interview Questions PDF By ScholarHat
Scholarhat
 
Entity Framework 6 Recipes 2nd Edition Brian Driscoll
raffygobahc9
 
[FREE PDF sample] Programming Entity Framework DbContext 1st Edition Julia Le...
pontyrincoe
 
Entity Framework Today (May 2012)
Julie Lerman
 
Entity Framework v1 and v2
Eric Nelson
 

More from Svetlin Nakov (20)

PPTX
AI and the Future of Devs: Nakov @ Techniverse (Nov 2024)
Svetlin Nakov
 
PPTX
AI за ежедневието - Наков @ Techniverse (Nov 2024)
Svetlin Nakov
 
PPTX
AI инструменти за бизнеса - Наков - Nov 2024
Svetlin Nakov
 
PPTX
AI Adoption in Business - Nakov at Forbes HR Forum - Sept 2024
Svetlin Nakov
 
PPTX
Software Engineers in the AI Era - Sept 2024
Svetlin Nakov
 
PPTX
Най-търсените направления в ИТ сферата за 2024
Svetlin Nakov
 
PPTX
BG-IT-Edu: отворено учебно съдържание за ИТ учители
Svetlin Nakov
 
PPTX
Programming World in 2024
Svetlin Nakov
 
PDF
AI Tools for Business and Startups
Svetlin Nakov
 
PPTX
AI Tools for Scientists - Nakov (Oct 2023)
Svetlin Nakov
 
PPTX
AI Tools for Entrepreneurs
Svetlin Nakov
 
PPTX
Bulgarian Tech Industry - Nakov at Dev.BG All in One Conference 2023
Svetlin Nakov
 
PPTX
AI Tools for Business and Personal Life
Svetlin Nakov
 
PDF
Дипломна работа: учебно съдържание по ООП - Светлин Наков
Svetlin Nakov
 
PPTX
Дипломна работа: учебно съдържание по ООП
Svetlin Nakov
 
PPTX
Свободно ИТ учебно съдържание за учители по програмиране и ИТ
Svetlin Nakov
 
PPTX
AI and the Professions of the Future
Svetlin Nakov
 
PPTX
Programming Languages Trends for 2023
Svetlin Nakov
 
PPTX
IT Professions and How to Become a Developer
Svetlin Nakov
 
PPTX
GitHub Actions (Nakov at RuseConf, Sept 2022)
Svetlin Nakov
 
AI and the Future of Devs: Nakov @ Techniverse (Nov 2024)
Svetlin Nakov
 
AI за ежедневието - Наков @ Techniverse (Nov 2024)
Svetlin Nakov
 
AI инструменти за бизнеса - Наков - Nov 2024
Svetlin Nakov
 
AI Adoption in Business - Nakov at Forbes HR Forum - Sept 2024
Svetlin Nakov
 
Software Engineers in the AI Era - Sept 2024
Svetlin Nakov
 
Най-търсените направления в ИТ сферата за 2024
Svetlin Nakov
 
BG-IT-Edu: отворено учебно съдържание за ИТ учители
Svetlin Nakov
 
Programming World in 2024
Svetlin Nakov
 
AI Tools for Business and Startups
Svetlin Nakov
 
AI Tools for Scientists - Nakov (Oct 2023)
Svetlin Nakov
 
AI Tools for Entrepreneurs
Svetlin Nakov
 
Bulgarian Tech Industry - Nakov at Dev.BG All in One Conference 2023
Svetlin Nakov
 
AI Tools for Business and Personal Life
Svetlin Nakov
 
Дипломна работа: учебно съдържание по ООП - Светлин Наков
Svetlin Nakov
 
Дипломна работа: учебно съдържание по ООП
Svetlin Nakov
 
Свободно ИТ учебно съдържание за учители по програмиране и ИТ
Svetlin Nakov
 
AI and the Professions of the Future
Svetlin Nakov
 
Programming Languages Trends for 2023
Svetlin Nakov
 
IT Professions and How to Become a Developer
Svetlin Nakov
 
GitHub Actions (Nakov at RuseConf, Sept 2022)
Svetlin Nakov
 

Recently uploaded (20)

PDF
The dynastic history of the Chahmana.pdf
PrachiSontakke5
 
PPTX
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
PDF
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
PDF
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
PPTX
SPINA BIFIDA: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
PDF
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
PDF
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
PPTX
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
PPTX
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
PDF
Lesson 2 - WATER,pH, BUFFERS, AND ACID-BASE.pdf
marvinnbustamante1
 
PDF
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - GLOBAL SUCCESS - CẢ NĂM - NĂM 2024 (VOCABULARY, ...
Nguyen Thanh Tu Collection
 
PPTX
How to Set Maximum Difference Odoo 18 POS
Celine George
 
PPTX
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
PDF
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
PPTX
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
PDF
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
PDF
LAW OF CONTRACT ( 5 YEAR LLB & UNITARY LLB)- MODULE-3 - LEARN THROUGH PICTURE
APARNA T SHAIL KUMAR
 
PPTX
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
PDF
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
PPTX
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
The dynastic history of the Chahmana.pdf
PrachiSontakke5
 
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
SPINA BIFIDA: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
Lesson 2 - WATER,pH, BUFFERS, AND ACID-BASE.pdf
marvinnbustamante1
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - GLOBAL SUCCESS - CẢ NĂM - NĂM 2024 (VOCABULARY, ...
Nguyen Thanh Tu Collection
 
How to Set Maximum Difference Odoo 18 POS
Celine George
 
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
LAW OF CONTRACT ( 5 YEAR LLB & UNITARY LLB)- MODULE-3 - LEARN THROUGH PICTURE
APARNA T SHAIL KUMAR
 
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 

Entity Framework: Nakov @ BFU Hackhaton 2015

  • 1. ORM Technologies and Entity Framework (EF) Entity Framework, DbContext, CRUD Operations, Code First, Migrations Svetlin Nakov Inspiration Manager Software University http://softuni.bg
  • 2. Table of Contents 1. ORM Technologies – Basic Concepts 2. Entity Framework – Overview 3. Database First with EF 4. Reading Data and CRUD operations with EF 5. Code First with EF  Domain Classes and DbContext 6. Migrations in EF 2
  • 3. Introduction to ORM Technologies What is Object-Relational Mapping (ORM)?
  • 4. 4  Object-Relational Mapping (ORM) is a programming technique for automatic mapping data and database schema  Map relational DB tables to classes and objects  ORM creates a "virtual object database"  Used from the programming language (C#, Java, PHP, …)  ORM frameworks automate the ORM process  A.k.a. Object-Relational Persistence Frameworks ORM Technologies
  • 5. 5 ORM Mapping – Example ORM Framework Relational database schema ORM Entities (C# classes)
  • 6. Entity Framework (EF) The ORM Framework for .NET
  • 7. 7  Entity Framework (EF) is the standard ORM framework for .NET  Maps relational database to C# object model  Powerful data manipulation API over the mapped schema  CRUD operations and complex querying with LINQ  Database first approach: from database to C# classes  Code first approach: from classes to DB schema  Visual Studio generates EF data models  Data mappings consist of C# classes, attributes and XML Overview of EF
  • 8. 8 EF: Basic Workflow 2. Write & execute query over IQueryable 3. EF generates & executes an SQL query in the DB 1. Define the data model (use a DB visual designer or code first)
  • 9. 9 EF: Basic Workflow (2) 5. Modify data with C# code and call "Save Changes" 6. Entity Framework generates & executes SQL command to modify the DB 4. EF transforms the query results into .NET objects
  • 10. 10  Install Entity Framework through the NuGet package manager Installing Entity Framework
  • 11. Database First with Entity Framework and Visual Studio Live Demo
  • 12. Entity Framework – Components  The DbContext class  DbContext holds the DB connection  Holds and DbSet<T> for the entity classes  Provides LINQ-based data access ( through IQueryable)  Provides API for CRUD operations  Entity classes  Hold entities (objects with their attributes and relations)  Each database table is typically mapped to a single C# entity class 12
  • 13. 13  We can also use extension methods for constructing the query  Find element by id Reading Data with LINQ Query using (var context = new SoftUniEntities()) { var project = context.Projects.Find(2); Console.WriteLine(project.Name); } using (var context = new SoftUniEntities()) { var employees = context.Employees .Select(c => c.FirstName) .Where(c => c.JobTitle == "Design Engineering") .ToList(); } This is called projection ToList() method executes the SQL query This is called selection
  • 14. 14  To create a new database row use the method Add(…) of the corresponding collection:  SaveChanges() method executes the SQL insert / update / delete commands in the database Creating New Data var project = new Project() { Name = "Judge System", StartDate = new DateTime(2015, 4, 15) }; context.Projects.Add(order); context.SaveChanges(); This will execute an SQL INSERT Create a new project object Mark the object for inserting
  • 15. 15  We can also add cascading entities to the database:  This way we don't have to add Project individually  They will be added when the Employee entity (employee) is inserted to the database Cascading Inserts Employee employee = new Employee(); employee.FirstName = "Petya"; employee.LastName = "Grozdarska"; employee.Projects.Add(new Project { Name = "SoftUni Conf" } ); softUniEntities.Employees.Add(employee); softUniEntities.SaveChanges();
  • 16. 16  DbContext allows modifying entity properties and persisting them in the database  Just load an entity, modify it and call SaveChanges()  The DbContext automatically tracks all changes made on its entity objects Updating Existing Data Employees employee = softUniEntities.Employees.First(); employees.FirstName = "Alex"; context.SaveChanges(); This will execute an SQL UPDATE This will execute an SQL SELECT to load the first order
  • 17. 17  Delete is done by Remove() on the specified entity collection  SaveChanges() method performs the delete action in the database Deleting Existing Data Employees employee = softUniEntities.Employees.First(); softUniEntities.Employees.Remove(employee); softUniEntities.SaveChanges(); Mark the entity for deleting at the next save This will execute the SQL DELETE command
  • 18. 18 Native SQL Queries var context = new SoftUniEntities(); string nativeSQLQuery = "SELECT FirstName + ' ' + LastName " + "FROM dbo.Employees WHERE JobTitle = {0}"; var employees = context.Database.SqlQuery<string>( nativeSQLQuery, "Marketing Specialist"); foreach (var emp in employees) { Console.WriteLine(emp); } Parameter placeholder Parameter value Return type
  • 19. CRUD Operations with EF Live Demo
  • 20. "Code First" Approach in EF From Classes to DB Schema
  • 21. 21  Create database schema and generate C# code (models) from it Database First in EF DB EDMX Model Domain Classes
  • 22. Code First in EF Custom Configuration DbContext & ModelBuilder Domain classes As needed DB 22
  • 23. Domain Classes (Models)  Bunch of normal C# classes (POCO)  May hold navigation properties public class PostAnswer { public int Id { get; set; } public string Content { get; set; } public int PostId { get; set; } public virtual Post Post { get; set; } } Primary key Foreign key Navigation property Virtual for lazy loading 23
  • 24. 24  Another example of domain class (model) Domain Classes (Models) (2) public class Post { public Post() { this.Answers = new HashSet<PostAnswer>(); } public virtual ICollection<PostAnswer> Answers { get; set; } public PostType Type { get; set; } } This prevents NullReferenceException Navigation property Enumeration
  • 25. 25 Defining the DbContext Class using System.Data.Entity; using CodeFirst.Models; public class ForumDbContext : DbContext { public DbSet<Category> Categories { get; set; } public DbSet<Post> Posts { get; set; } public DbSet<PostAnswer> PostAnswers { get; set; } public DbSet<Tag> Tags { get; set; } } Put all entity classes as DbSets
  • 26. CRUD Operations with EF Code First var db = new ForumDbContext(); var category = new Category { Name = "Database course" }; db.Categories.Add(category); var post = new Post(); post.Title = "Homework Deadline"; post.Content = "Please extend the homework deadline"; post.Type = PostType.Normal; post.Category = category; post.Tags.Add(new Tag { Text = "homework" }); post.Tags.Add(new Tag { Text = "deadline" }); db.Posts.Add(post); db.SaveChanges(); 26
  • 27. "Code First" Approach in EF Live Demo
  • 28. Using Code First Migrations in EF
  • 29. 29  Enable Code First Migrations  Open Package Manager Console  Run Enable-Migrations command  -EnableAutomaticMigrations for auto migrations Code First Migrations in Entity Framework
  • 30. 30 Configuring the Migration Strategy // Enable automatic DB migrations for ForumDbContext Database.SetInitializer( new MigrateDatabaseToLatestVersion< ForumDbContext, DbMigrationConfig>()); class DbMigrationConfig : DbMigrationsConfiguration<ForumDbContext> { public Configuration() { AutomaticMigrationsEnabled = true; AutomaticMigrationDataLossAllowed = true; } }
  • 31. Using Code First Migrations in EF Live Demo
  • 33. Free Trainings @ Software University  Software University Foundation – softuni.org  Software University – High-Quality Education, Profession and Job for Software Developers  softuni.bg  Software University @ Facebook  facebook.com/SoftwareUniversity  Software University @ YouTube  youtube.com/SoftwareUniversity  Software University Forums – forum.softuni.bg