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

Entity Framework Overview
Entity Framework OverviewEntity Framework Overview
Entity Framework OverviewEric Nelson
 
Entity framework code first
Entity framework code firstEntity framework code first
Entity framework code firstConfiz
 
Introduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesIntroduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesecosio GmbH
 
Database Programming Techniques
Database Programming TechniquesDatabase Programming Techniques
Database Programming TechniquesRaji Ghawi
 
Introduction to Hibernate Framework
Introduction to Hibernate FrameworkIntroduction to Hibernate Framework
Introduction to Hibernate FrameworkRaveendra R
 
Hibernate An Introduction
Hibernate An IntroductionHibernate An Introduction
Hibernate An IntroductionNguyen Cao
 
Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentationManav Prasad
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate pptAneega
 
Spring (1)
Spring (1)Spring (1)
Spring (1)Aneega
 
C# Advanced L07-Design Patterns
C# Advanced L07-Design PatternsC# Advanced L07-Design Patterns
C# Advanced L07-Design PatternsMohammad Shaker
 
jpa-hibernate-presentation
jpa-hibernate-presentationjpa-hibernate-presentation
jpa-hibernate-presentationJohn Slick
 

What's hot (20)

Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
Entity Framework Overview
Entity Framework OverviewEntity Framework Overview
Entity Framework Overview
 
Entity framework code first
Entity framework code firstEntity framework code first
Entity framework code first
 
Introduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesIntroduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examples
 
Database Programming Techniques
Database Programming TechniquesDatabase Programming Techniques
Database Programming Techniques
 
Introduction to Hibernate Framework
Introduction to Hibernate FrameworkIntroduction to Hibernate Framework
Introduction to Hibernate Framework
 
Data access
Data accessData access
Data access
 
Hibernate An Introduction
Hibernate An IntroductionHibernate An Introduction
Hibernate An Introduction
 
Jdbc
JdbcJdbc
Jdbc
 
Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentation
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate ppt
 
Introduction to JPA Framework
Introduction to JPA FrameworkIntroduction to JPA Framework
Introduction to JPA Framework
 
Introduction to Hibernate
Introduction to HibernateIntroduction to Hibernate
Introduction to Hibernate
 
Java Programming - 08 java threading
Java Programming - 08 java threadingJava Programming - 08 java threading
Java Programming - 08 java threading
 
hibernate with JPA
hibernate with JPAhibernate with JPA
hibernate with JPA
 
Hibernate in Nutshell
Hibernate in NutshellHibernate in Nutshell
Hibernate in Nutshell
 
Spring (1)
Spring (1)Spring (1)
Spring (1)
 
Advanced core java
Advanced core javaAdvanced core java
Advanced core java
 
C# Advanced L07-Design Patterns
C# Advanced L07-Design PatternsC# Advanced L07-Design Patterns
C# Advanced L07-Design Patterns
 
jpa-hibernate-presentation
jpa-hibernate-presentationjpa-hibernate-presentation
jpa-hibernate-presentation
 

Viewers also liked

Regular Expressions: QA Challenge Accepted Conf (March 2015)
Regular Expressions: QA Challenge Accepted Conf (March 2015)Regular Expressions: QA Challenge Accepted Conf (March 2015)
Regular Expressions: QA Challenge Accepted Conf (March 2015)Svetlin Nakov
 
05 entity framework
05 entity framework05 entity framework
05 entity frameworkglubox
 
SUE AGILE MVVM (Italian)
SUE AGILE MVVM (Italian)SUE AGILE MVVM (Italian)
SUE AGILE MVVM (Italian)Sabino Labarile
 
Slide typescript - xe dotnet - Codemotion Rome 2015
Slide typescript - xe dotnet - Codemotion Rome 2015Slide typescript - xe dotnet - Codemotion Rome 2015
Slide typescript - xe dotnet - Codemotion Rome 2015Codemotion
 
Nakov at Fuck Up Nights - July 2015 @ Sofia
Nakov at Fuck Up Nights - July 2015 @ SofiaNakov at Fuck Up Nights - July 2015 @ Sofia
Nakov at Fuck Up Nights - July 2015 @ SofiaSvetlin Nakov
 
Следвай вдъхновението си! (фестивал "Свободата да бъдеш - април 2016")
Следвай вдъхновението си! (фестивал "Свободата да бъдеш - април 2016")Следвай вдъхновението си! (фестивал "Свободата да бъдеш - април 2016")
Следвай вдъхновението си! (фестивал "Свободата да бъдеш - април 2016")Svetlin Nakov
 
Slide Prelaurea. Alessandro Andreosè
Slide Prelaurea. Alessandro AndreosèSlide Prelaurea. Alessandro Andreosè
Slide Prelaurea. Alessandro Andreosèguesta10af3
 
Introduzione a MVVM e Caliburn.Micro
Introduzione a MVVM e Caliburn.MicroIntroduzione a MVVM e Caliburn.Micro
Introduzione a MVVM e Caliburn.MicroMassimo Bonanni
 
Професия "програмист"
Професия "програмист"Професия "програмист"
Професия "програмист"Svetlin Nakov
 
Dependency Injection and Inversion Of Control
Dependency Injection and Inversion Of ControlDependency Injection and Inversion Of Control
Dependency Injection and Inversion Of ControlSimone Busoli
 
ORM: Object-relational mapping
ORM: Object-relational mappingORM: Object-relational mapping
ORM: Object-relational mappingAbhilash M A
 
Inversion of Control @ CD2008
Inversion of Control @ CD2008Inversion of Control @ CD2008
Inversion of Control @ CD2008Mauro Servienti
 
Как да станем софтуерни инженери и да стартираме ИТ бизнес?
Как да станем софтуерни инженери и да стартираме ИТ бизнес?Как да станем софтуерни инженери и да стартираме ИТ бизнес?
Как да станем софтуерни инженери и да стартираме ИТ бизнес?Svetlin Nakov
 
Model-View-ViewModel
Model-View-ViewModelModel-View-ViewModel
Model-View-ViewModelDotNetMarche
 
Работа с Естествен Интелект – Личност – Време – 3 юли 2013 @ НЛП клуб
Работа с Естествен Интелект – Личност – Време – 3 юли 2013 @ НЛП клубРабота с Естествен Интелект – Личност – Време – 3 юли 2013 @ НЛП клуб
Работа с Естествен Интелект – Личност – Време – 3 юли 2013 @ НЛП клубSvetlin Nakov
 
Architetttura Della Soluzione
Architetttura Della SoluzioneArchitetttura Della Soluzione
Architetttura Della SoluzioneLuca Milan
 

Viewers also liked (20)

Regular Expressions: QA Challenge Accepted Conf (March 2015)
Regular Expressions: QA Challenge Accepted Conf (March 2015)Regular Expressions: QA Challenge Accepted Conf (March 2015)
Regular Expressions: QA Challenge Accepted Conf (March 2015)
 
Why not ORM
Why not ORMWhy not ORM
Why not ORM
 
05 entity framework
05 entity framework05 entity framework
05 entity framework
 
SUE AGILE MVVM (Italian)
SUE AGILE MVVM (Italian)SUE AGILE MVVM (Italian)
SUE AGILE MVVM (Italian)
 
Slide typescript - xe dotnet - Codemotion Rome 2015
Slide typescript - xe dotnet - Codemotion Rome 2015Slide typescript - xe dotnet - Codemotion Rome 2015
Slide typescript - xe dotnet - Codemotion Rome 2015
 
System.AddIn @ Xe.Net
System.AddIn @ Xe.NetSystem.AddIn @ Xe.Net
System.AddIn @ Xe.Net
 
Nakov at Fuck Up Nights - July 2015 @ Sofia
Nakov at Fuck Up Nights - July 2015 @ SofiaNakov at Fuck Up Nights - July 2015 @ Sofia
Nakov at Fuck Up Nights - July 2015 @ Sofia
 
Следвай вдъхновението си! (фестивал "Свободата да бъдеш - април 2016")
Следвай вдъхновението си! (фестивал "Свободата да бъдеш - април 2016")Следвай вдъхновението си! (фестивал "Свободата да бъдеш - април 2016")
Следвай вдъхновението си! (фестивал "Свободата да бъдеш - април 2016")
 
Slide Prelaurea. Alessandro Andreosè
Slide Prelaurea. Alessandro AndreosèSlide Prelaurea. Alessandro Andreosè
Slide Prelaurea. Alessandro Andreosè
 
Introduzione a MVVM e Caliburn.Micro
Introduzione a MVVM e Caliburn.MicroIntroduzione a MVVM e Caliburn.Micro
Introduzione a MVVM e Caliburn.Micro
 
Професия "програмист"
Професия "програмист"Професия "програмист"
Професия "програмист"
 
Dependency Injection and Inversion Of Control
Dependency Injection and Inversion Of ControlDependency Injection and Inversion Of Control
Dependency Injection and Inversion Of Control
 
ORM: Object-relational mapping
ORM: Object-relational mappingORM: Object-relational mapping
ORM: Object-relational mapping
 
Inversion of Control @ CD2008
Inversion of Control @ CD2008Inversion of Control @ CD2008
Inversion of Control @ CD2008
 
Как да станем софтуерни инженери и да стартираме ИТ бизнес?
Как да станем софтуерни инженери и да стартираме ИТ бизнес?Как да станем софтуерни инженери и да стартираме ИТ бизнес?
Как да станем софтуерни инженери и да стартираме ИТ бизнес?
 
Model-View-ViewModel
Model-View-ViewModelModel-View-ViewModel
Model-View-ViewModel
 
Работа с Естествен Интелект – Личност – Време – 3 юли 2013 @ НЛП клуб
Работа с Естествен Интелект – Личност – Време – 3 юли 2013 @ НЛП клубРабота с Естествен Интелект – Личност – Време – 3 юли 2013 @ НЛП клуб
Работа с Естествен Интелект – Личност – Време – 3 юли 2013 @ НЛП клуб
 
Architetttura Della Soluzione
Architetttura Della SoluzioneArchitetttura Della Soluzione
Architetttura Della Soluzione
 
UI Composition
UI CompositionUI Composition
UI Composition
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 

Similar to Entity Framework: Nakov @ BFU Hackhaton 2015

MVC and Entity Framework
MVC and Entity FrameworkMVC and Entity Framework
MVC and Entity FrameworkJames Johnson
 
dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...
dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...
dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...dotNet Miami
 
State of entity framework
State of entity frameworkState of entity framework
State of entity frameworkDavid Paquette
 
Session 24 - JDBC, Intro to Enterprise Java
Session 24 - JDBC, Intro to Enterprise JavaSession 24 - JDBC, Intro to Enterprise Java
Session 24 - JDBC, Intro to Enterprise JavaPawanMM
 
MVC and Entity Framework 4
MVC and Entity Framework 4MVC and Entity Framework 4
MVC and Entity Framework 4James Johnson
 
Hibernate
Hibernate Hibernate
Hibernate Sunil OS
 
Viastudy ef core_cheat_sheet
Viastudy ef core_cheat_sheetViastudy ef core_cheat_sheet
Viastudy ef core_cheat_sheetimdurgesh
 
JDK1.7 features
JDK1.7 featuresJDK1.7 features
JDK1.7 featuresindia_mani
 
Spring framework part 2
Spring framework part 2Spring framework part 2
Spring framework part 2Haroon Idrees
 
A brief overview of java frameworks
A brief overview of java frameworksA brief overview of java frameworks
A brief overview of java frameworksMD Sayem Ahmed
 
Entity framework (EF) 7
Entity framework (EF) 7Entity framework (EF) 7
Entity framework (EF) 7Paul Graham
 
jdbc_presentation.ppt
jdbc_presentation.pptjdbc_presentation.ppt
jdbc_presentation.pptDrMeenakshiS
 
Local data storage for mobile apps
Local data storage for mobile appsLocal data storage for mobile apps
Local data storage for mobile appsIvano Malavolta
 

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

MVC and Entity Framework
MVC and Entity FrameworkMVC and Entity Framework
MVC and Entity Framework
 
dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...
dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...
dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...
 
State of entity framework
State of entity frameworkState of entity framework
State of entity framework
 
Intake 37 ef2
Intake 37 ef2Intake 37 ef2
Intake 37 ef2
 
La sql
La sqlLa sql
La sql
 
JDBC Part - 2
JDBC Part - 2JDBC Part - 2
JDBC Part - 2
 
Lecture17
Lecture17Lecture17
Lecture17
 
Session 24 - JDBC, Intro to Enterprise Java
Session 24 - JDBC, Intro to Enterprise JavaSession 24 - JDBC, Intro to Enterprise Java
Session 24 - JDBC, Intro to Enterprise Java
 
MVC and Entity Framework 4
MVC and Entity Framework 4MVC and Entity Framework 4
MVC and Entity Framework 4
 
Hibernate
Hibernate Hibernate
Hibernate
 
Viastudy ef core_cheat_sheet
Viastudy ef core_cheat_sheetViastudy ef core_cheat_sheet
Viastudy ef core_cheat_sheet
 
JDK1.7 features
JDK1.7 featuresJDK1.7 features
JDK1.7 features
 
Spring framework part 2
Spring framework part 2Spring framework part 2
Spring framework part 2
 
A brief overview of java frameworks
A brief overview of java frameworksA brief overview of java frameworks
A brief overview of java frameworks
 
Real World MVC
Real World MVCReal World MVC
Real World MVC
 
Entity framework (EF) 7
Entity framework (EF) 7Entity framework (EF) 7
Entity framework (EF) 7
 
jdbc_presentation.ppt
jdbc_presentation.pptjdbc_presentation.ppt
jdbc_presentation.ppt
 
Jsp project module
Jsp project moduleJsp project module
Jsp project module
 
Local data storage for mobile apps
Local data storage for mobile appsLocal data storage for mobile apps
Local data storage for mobile apps
 
Intake 37 linq3
Intake 37 linq3Intake 37 linq3
Intake 37 linq3
 

More from Svetlin Nakov

BG-IT-Edu: отворено учебно съдържание за ИТ учители
BG-IT-Edu: отворено учебно съдържание за ИТ учителиBG-IT-Edu: отворено учебно съдържание за ИТ учители
BG-IT-Edu: отворено учебно съдържание за ИТ учителиSvetlin Nakov
 
Programming World in 2024
Programming World in 2024Programming World in 2024
Programming World in 2024Svetlin Nakov
 
AI Tools for Business and Startups
AI Tools for Business and StartupsAI Tools for Business and Startups
AI Tools for Business and StartupsSvetlin Nakov
 
AI Tools for Scientists - Nakov (Oct 2023)
AI Tools for Scientists - Nakov (Oct 2023)AI Tools for Scientists - Nakov (Oct 2023)
AI Tools for Scientists - Nakov (Oct 2023)Svetlin Nakov
 
AI Tools for Entrepreneurs
AI Tools for EntrepreneursAI Tools for Entrepreneurs
AI Tools for EntrepreneursSvetlin Nakov
 
Bulgarian Tech Industry - Nakov at Dev.BG All in One Conference 2023
Bulgarian Tech Industry - Nakov at Dev.BG All in One Conference 2023Bulgarian Tech Industry - Nakov at Dev.BG All in One Conference 2023
Bulgarian Tech Industry - Nakov at Dev.BG All in One Conference 2023Svetlin Nakov
 
AI Tools for Business and Personal Life
AI Tools for Business and Personal LifeAI Tools for Business and Personal Life
AI Tools for Business and Personal LifeSvetlin Nakov
 
Дипломна работа: учебно съдържание по ООП - Светлин Наков
Дипломна работа: учебно съдържание по ООП - Светлин НаковДипломна работа: учебно съдържание по ООП - Светлин Наков
Дипломна работа: учебно съдържание по ООП - Светлин НаковSvetlin Nakov
 
Дипломна работа: учебно съдържание по ООП
Дипломна работа: учебно съдържание по ООПДипломна работа: учебно съдържание по ООП
Дипломна работа: учебно съдържание по ООПSvetlin Nakov
 
Свободно ИТ учебно съдържание за учители по програмиране и ИТ
Свободно ИТ учебно съдържание за учители по програмиране и ИТСвободно ИТ учебно съдържание за учители по програмиране и ИТ
Свободно ИТ учебно съдържание за учители по програмиране и ИТSvetlin Nakov
 
AI and the Professions of the Future
AI and the Professions of the FutureAI and the Professions of the Future
AI and the Professions of the FutureSvetlin Nakov
 
Programming Languages Trends for 2023
Programming Languages Trends for 2023Programming Languages Trends for 2023
Programming Languages Trends for 2023Svetlin Nakov
 
IT Professions and How to Become a Developer
IT Professions and How to Become a DeveloperIT Professions and How to Become a Developer
IT Professions and How to Become a DeveloperSvetlin Nakov
 
GitHub Actions (Nakov at RuseConf, Sept 2022)
GitHub Actions (Nakov at RuseConf, Sept 2022)GitHub Actions (Nakov at RuseConf, Sept 2022)
GitHub Actions (Nakov at RuseConf, Sept 2022)Svetlin Nakov
 
IT Professions and Their Future
IT Professions and Their FutureIT Professions and Their Future
IT Professions and Their FutureSvetlin Nakov
 
How to Become a QA Engineer and Start a Job
How to Become a QA Engineer and Start a JobHow to Become a QA Engineer and Start a Job
How to Become a QA Engineer and Start a JobSvetlin Nakov
 
Призвание и цели: моята рецепта
Призвание и цели: моята рецептаПризвание и цели: моята рецепта
Призвание и цели: моята рецептаSvetlin Nakov
 
What Mongolian IT Industry Can Learn from Bulgaria?
What Mongolian IT Industry Can Learn from Bulgaria?What Mongolian IT Industry Can Learn from Bulgaria?
What Mongolian IT Industry Can Learn from Bulgaria?Svetlin Nakov
 
How to Become a Software Developer - Nakov in Mongolia (Oct 2022)
How to Become a Software Developer - Nakov in Mongolia (Oct 2022)How to Become a Software Developer - Nakov in Mongolia (Oct 2022)
How to Become a Software Developer - Nakov in Mongolia (Oct 2022)Svetlin Nakov
 
Blockchain and DeFi Overview (Nakov, Sept 2021)
Blockchain and DeFi Overview (Nakov, Sept 2021)Blockchain and DeFi Overview (Nakov, Sept 2021)
Blockchain and DeFi Overview (Nakov, Sept 2021)Svetlin Nakov
 

More from Svetlin Nakov (20)

BG-IT-Edu: отворено учебно съдържание за ИТ учители
BG-IT-Edu: отворено учебно съдържание за ИТ учителиBG-IT-Edu: отворено учебно съдържание за ИТ учители
BG-IT-Edu: отворено учебно съдържание за ИТ учители
 
Programming World in 2024
Programming World in 2024Programming World in 2024
Programming World in 2024
 
AI Tools for Business and Startups
AI Tools for Business and StartupsAI Tools for Business and Startups
AI Tools for Business and Startups
 
AI Tools for Scientists - Nakov (Oct 2023)
AI Tools for Scientists - Nakov (Oct 2023)AI Tools for Scientists - Nakov (Oct 2023)
AI Tools for Scientists - Nakov (Oct 2023)
 
AI Tools for Entrepreneurs
AI Tools for EntrepreneursAI Tools for Entrepreneurs
AI Tools for Entrepreneurs
 
Bulgarian Tech Industry - Nakov at Dev.BG All in One Conference 2023
Bulgarian Tech Industry - Nakov at Dev.BG All in One Conference 2023Bulgarian Tech Industry - Nakov at Dev.BG All in One Conference 2023
Bulgarian Tech Industry - Nakov at Dev.BG All in One Conference 2023
 
AI Tools for Business and Personal Life
AI Tools for Business and Personal LifeAI Tools for Business and Personal Life
AI Tools for Business and Personal Life
 
Дипломна работа: учебно съдържание по ООП - Светлин Наков
Дипломна работа: учебно съдържание по ООП - Светлин НаковДипломна работа: учебно съдържание по ООП - Светлин Наков
Дипломна работа: учебно съдържание по ООП - Светлин Наков
 
Дипломна работа: учебно съдържание по ООП
Дипломна работа: учебно съдържание по ООПДипломна работа: учебно съдържание по ООП
Дипломна работа: учебно съдържание по ООП
 
Свободно ИТ учебно съдържание за учители по програмиране и ИТ
Свободно ИТ учебно съдържание за учители по програмиране и ИТСвободно ИТ учебно съдържание за учители по програмиране и ИТ
Свободно ИТ учебно съдържание за учители по програмиране и ИТ
 
AI and the Professions of the Future
AI and the Professions of the FutureAI and the Professions of the Future
AI and the Professions of the Future
 
Programming Languages Trends for 2023
Programming Languages Trends for 2023Programming Languages Trends for 2023
Programming Languages Trends for 2023
 
IT Professions and How to Become a Developer
IT Professions and How to Become a DeveloperIT Professions and How to Become a Developer
IT Professions and How to Become a Developer
 
GitHub Actions (Nakov at RuseConf, Sept 2022)
GitHub Actions (Nakov at RuseConf, Sept 2022)GitHub Actions (Nakov at RuseConf, Sept 2022)
GitHub Actions (Nakov at RuseConf, Sept 2022)
 
IT Professions and Their Future
IT Professions and Their FutureIT Professions and Their Future
IT Professions and Their Future
 
How to Become a QA Engineer and Start a Job
How to Become a QA Engineer and Start a JobHow to Become a QA Engineer and Start a Job
How to Become a QA Engineer and Start a Job
 
Призвание и цели: моята рецепта
Призвание и цели: моята рецептаПризвание и цели: моята рецепта
Призвание и цели: моята рецепта
 
What Mongolian IT Industry Can Learn from Bulgaria?
What Mongolian IT Industry Can Learn from Bulgaria?What Mongolian IT Industry Can Learn from Bulgaria?
What Mongolian IT Industry Can Learn from Bulgaria?
 
How to Become a Software Developer - Nakov in Mongolia (Oct 2022)
How to Become a Software Developer - Nakov in Mongolia (Oct 2022)How to Become a Software Developer - Nakov in Mongolia (Oct 2022)
How to Become a Software Developer - Nakov in Mongolia (Oct 2022)
 
Blockchain and DeFi Overview (Nakov, Sept 2021)
Blockchain and DeFi Overview (Nakov, Sept 2021)Blockchain and DeFi Overview (Nakov, Sept 2021)
Blockchain and DeFi Overview (Nakov, Sept 2021)
 

Recently uploaded

Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
Romantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxRomantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxsqpmdrvczh
 
Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........LeaCamillePacle
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 

Recently uploaded (20)

Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
Romantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxRomantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptx
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 

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