SlideShare ist ein Scribd-Unternehmen logo
1 von 62
ADO.NET EntityADO.NET Entity
FrameworkFramework
ORM Concepts, ADO.NET EntityORM Concepts, ADO.NET Entity
Framework (EF),Framework (EF), ObjectContextObjectContext
Doncho MinkovDoncho Minkov
Telerik School AcademyTelerik School Academy
schoolacademy.telerik.comschoolacademy.telerik.com
Technical TrainerTechnical Trainer
http://www.minkov.ithttp://www.minkov.it
Table of ContentsTable of Contents
 ORM Technologies – Basic ConceptsORM Technologies – Basic Concepts
 Entity FrameworkEntity Framework
OverviewOverview
Printing the native SQL queriesPrinting the native SQL queries
LINQ ComponentsLINQ Components
Entity FilesEntity Files
The Visual Studio DesignerThe Visual Studio Designer
ObjectContextObjectContext Class and CRUD OperationsClass and CRUD Operations
2
Table of Contents (2)Table of Contents (2)
 Executing Native SQL QueriesExecuting Native SQL Queries
Paramerterless QueriesParamerterless Queries
Parameterized QueriesParameterized Queries
 The N+1 Query ProblemThe N+1 Query Problem
 Joining and Grouping EntitiesJoining and Grouping Entities
 Attaching and Detaching ObjectsAttaching and Detaching Objects
3
Introduction to ORMIntroduction to ORM
Object-Relational Mapping (ORM)TechnologiesObject-Relational Mapping (ORM)Technologies
ORM TechnologiesORM Technologies
 Object-Relational Mapping (ORM)Object-Relational Mapping (ORM) is ais a
programming technique for automaticprogramming technique for automatic
mapping and converting datamapping and converting data
Between relational database tables and object-Between relational database tables and object-
oriented classes and objectsoriented classes and objects
 ORM creates a “virtual object database“ORM creates a “virtual object database“
Which can be used from within theWhich can be used from within the
programming language, e.g. C# or Javaprogramming language, e.g. C# or Java
 ORM frameworksORM frameworks automate the ORM processautomate the ORM process
A.k.a.A.k.a. object-relational persistence frameworksobject-relational persistence frameworks
5
ORM FrameworksORM Frameworks
 ORMORM frameworksframeworks typically provide thetypically provide the
following functionality:following functionality:
Creating object model by database schemaCreating object model by database schema
Creating database schema by object modelCreating database schema by object model
Querying data by object-oriented APIQuerying data by object-oriented API
Data manipulation operationsData manipulation operations
 CRUDCRUD – create, retrieve, update, delete– create, retrieve, update, delete
 ORMORM frameworksframeworks automatically generate SQLautomatically generate SQL
to perform the requested data operationsto perform the requested data operations
6
ORM Mapping – ExampleORM Mapping – Example
 Database and Entities mapping diagrams for aDatabase and Entities mapping diagrams for a
subset of thesubset of the NorthwindNorthwind databasedatabase
7
RelationalRelational
databasedatabase
schemaschema
ORMORM
Entities (C#Entities (C#
Classes)Classes)
ORMORM
FrameworFramewor
kk
ORM AdvantagesORM Advantages
 Object-relational mapping advantagesObject-relational mapping advantages
Developer productivityDeveloper productivity
 Writing less codeWriting less code
Abstract from differences between object andAbstract from differences between object and
relational worldrelational world
 Complexity hidden within ORMComplexity hidden within ORM
Manageability of the CRUD operations forManageability of the CRUD operations for
complex relationshipscomplex relationships
Easier maintainabilityEasier maintainability
8
Approaches to ORMApproaches to ORM
 Template-based code generation vs. entityTemplate-based code generation vs. entity
classes mappingsclasses mappings
 SQL generation (design time / runtime) vs.SQL generation (design time / runtime) vs.
mapping existing SQLmapping existing SQL
 Entity classes representationEntity classes representation
Entities are just POCO (Plain Old C# Objects)Entities are just POCO (Plain Old C# Objects)
Entities implementEntities implement specialspecial IPersistentIPersistent
interface or extendinterface or extend PersistentBasePersistentBase classclass
 Configuring mappingsConfiguring mappings
DB schema data vs. XML vs. annotationsDB schema data vs. XML vs. annotations
9
Object Persistence FrameworksObject Persistence Frameworks
 Code generation toolsCode generation tools
Generate C#, XML and other filesGenerate C#, XML and other files
Source code is compiled and used as APISource code is compiled and used as API
Can be highly customizedCan be highly customized
 Object-relational mapping toolsObject-relational mapping tools
Mappings are described in XML files or built inMappings are described in XML files or built in
the classes as attributesthe classes as attributes
No source code generationNo source code generation
Use of single standard APIUse of single standard API
10
ORM Frameworks in .NETORM Frameworks in .NET
 Built-in ORM tools in .NET Framework and VSBuilt-in ORM tools in .NET Framework and VS
ADO.NET Entity FrameworkADO.NET Entity Framework
LINQ-to-SQLLINQ-to-SQL
Both combine entity class mappings and codeBoth combine entity class mappings and code
generation, SQL is generated at runtimegeneration, SQL is generated at runtime
 Third party ORM toolsThird party ORM tools
NHibernateNHibernate – the old daddy of ORM– the old daddy of ORM
Telerik OpenAccess ORMTelerik OpenAccess ORM
11
ADO.NET Entity FrameworkADO.NET Entity Framework
Object Relation Persistence FrameworkObject Relation Persistence Framework
Overview of ADO.NET EFOverview of ADO.NET EF
 Entity Framework (EF)Entity Framework (EF) is a standard ORMis a standard ORM
framework, part of .NETframework, part of .NET
Provides a run-time infrastructure for managingProvides a run-time infrastructure for managing
SQL-based database data as .NET objectsSQL-based database data as .NET objects
 The relational database schema is mapped toThe relational database schema is mapped to
an object model (classes and associations)an object model (classes and associations)
Visual Studio has built-in tools for generatingVisual Studio has built-in tools for generating
Entity FrameworkEntity Framework SQL data mappingsSQL data mappings
 Data mappings consist of C# classes and XMLData mappings consist of C# classes and XML
A standard data manipulation API is providedA standard data manipulation API is provided
13
Overview of ADO.NET EF (2)Overview of ADO.NET EF (2)
 Entity FrameworkEntity Framework provides an applicationprovides an application
programming interface (API)programming interface (API)
For accessing data stored in database serversFor accessing data stored in database servers
Built on the top of ADO.NET and LINQBuilt on the top of ADO.NET and LINQ
 LINQ to EntitiesLINQ to Entities is Microsoft’s entry-levelis Microsoft’s entry-level
LINQ-enabled ORM implementation forLINQ-enabled ORM implementation for
database serversdatabase servers
Works with SQL Server and SQL Server ExpressWorks with SQL Server and SQL Server Express
Could work with MySQL, SQLite, Oracle, etc.Could work with MySQL, SQLite, Oracle, etc.
Maps tables and one-to-many and many-to-Maps tables and one-to-many and many-to-
many relationshipsmany relationships
14
Entity Data ModelEntity Data Model
 TheThe Entity Data Model (EDM)Entity Data Model (EDM) is a schemais a schema
language for entities, consisting of:language for entities, consisting of:
Conceptual model (CSDL)Conceptual model (CSDL)
Mapping (MSL)Mapping (MSL)
Storage Model (SSDL)Storage Model (SSDL)
15
Entity Framework ArchitectureEntity Framework Architecture
16
Entity Framework FeaturesEntity Framework Features
 Entity Framework (EF)Entity Framework (EF) standard features:standard features:
Maps tables, views, stored procedures andMaps tables, views, stored procedures and
functions as .NET objectsfunctions as .NET objects
Provides LINQ-based data queriesProvides LINQ-based data queries
 Executed asExecuted as SQLSQL SELECTsSELECTs on the database serveron the database server
CRUD operations –CRUD operations – CreateCreate//ReadRead//UpdateUpdate//DeleteDelete
Create compiled queries – for executing theCreate compiled queries – for executing the
same parameterized query multiple timessame parameterized query multiple times
Creating or deleting the database schemaCreating or deleting the database schema
17
Entity Framework LifecycleEntity Framework Lifecycle
 When the application startsWhen the application starts
EFEF translates into SQL the language-integratedtranslates into SQL the language-integrated
queries in the object modelqueries in the object model
Sends them to the database for later executionSends them to the database for later execution
18
Entity Framework Lifecycle (2)Entity Framework Lifecycle (2)
 When the database returns the resultsWhen the database returns the results
Entity FrameworkEntity Framework translates the database rowstranslates the database rows
back to .NET objectsback to .NET objects
 The database server is transparent, hiddenThe database server is transparent, hidden
behind the APIbehind the API
 LINQ is executed overLINQ is executed over IQueryable<T>IQueryable<T>
 At compile time a query expression tree isAt compile time a query expression tree is
emittedemitted
 At runtime SQL is generated and executedAt runtime SQL is generated and executed
19
EF ComponentsEF Components
 TheThe ObjectContextObjectContext classclass
ObjectContextObjectContext holds the database connectionholds the database connection
and the entity classesand the entity classes
Provides LINQ-based data accessProvides LINQ-based data access
Implements identity tracking, change tracking,Implements identity tracking, change tracking,
and API for CRUD operationsand API for CRUD operations
 Entity classesEntity classes
Each database table is typically mapped to aEach database table is typically mapped to a
single entity class (C# class)single entity class (C# class)
20
EF Components (2)EF Components (2)
 AssociationsAssociations
An association is a primary key / foreign keyAn association is a primary key / foreign key
based relationship between two entity classesbased relationship between two entity classes
Allows navigation from one entity to another,Allows navigation from one entity to another,
e.g.e.g. Student.CoursesStudent.Courses
 Concurrency controlConcurrency control
EntityEntity FrameworkFramework uses optimistic concurrencyuses optimistic concurrency
control (no locking by default)control (no locking by default)
Provides automatic concurrency conflictProvides automatic concurrency conflict
detection and means for conflicts resolutiondetection and means for conflicts resolution
21
LINQ to Entity Files (.LINQ to Entity Files (.edmxedmx))
 Visual Studio has built-in Entity FrameworkVisual Studio has built-in Entity Framework
data designer and code generatordata designer and code generator
Mappings are stored inMappings are stored in .edmx.edmx files (files (EEntityntity DDataata
MModelodel XXMLML))
<database>.edmx<database>.edmx is an XML fileis an XML file
 Holds metadata representing the databaseHolds metadata representing the database
schema (CSDL, MSL and SSDL models)schema (CSDL, MSL and SSDL models)
<database>.Designer.cs<database>.Designer.cs file contains the C#file contains the C#
entity classes and theentity classes and the ObjectContextObjectContext classclass
 One entity class for each mapped database tableOne entity class for each mapped database table
22
LINQ to Entity Files – ExampleLINQ to Entity Files – Example
 EDMXEDMX mapping for themapping for the CategoriesCategories tabletable
fromfrom NorthwindNorthwind database in SQL Serverdatabase in SQL Server
23
<EntityType Name="Categories"><EntityType Name="Categories">
<Key><Key>
<PropertyRef Name="CategoryID" /><PropertyRef Name="CategoryID" />
</Key></Key>
<Property Name="CategoryID" Nullable="false"<Property Name="CategoryID" Nullable="false"
Type="int" StoreGeneratedPattern="Identity" />Type="int" StoreGeneratedPattern="Identity" />
<Property Name="CategoryName" Type="nvarchar"<Property Name="CategoryName" Type="nvarchar"
Nullable="false" MaxLength="15" />Nullable="false" MaxLength="15" />
<Property Name="Description" Type="ntext"<Property Name="Description" Type="ntext" />/>
<Property Name="Picture" Type="image" /><Property Name="Picture" Type="image" />
</EntityType></EntityType>
EntityEntity
classclass
CategoryCategory
The Entity FrameworkThe Entity Framework
DesignerDesigner inVisual StudioinVisual Studio
Live DemoLive Demo
TheThe ObjectContextObjectContext ClassClass
 TheThe ObjectContextObjectContext class is generated by theclass is generated by the
Visual Studio designerVisual Studio designer
 ObjectObjectContextContext provides:provides:
Methods for accessing entities (object sets) andMethods for accessing entities (object sets) and
creating new entities (creating new entities (AddToAddTo…… methods)methods)
Ability to manipulate database data thoughAbility to manipulate database data though
entity classes (read, modify, delete, insert)entity classes (read, modify, delete, insert)
Easily navigate through the table relationshipsEasily navigate through the table relationships
Executing LINQ queries as native SQL queriesExecuting LINQ queries as native SQL queries
Create the DB schema in the database serverCreate the DB schema in the database server
25
Using ObjectContext ClassUsing ObjectContext Class
 First create instance of theFirst create instance of the ObjectContextObjectContext::
 In the constructor you can pass a databaseIn the constructor you can pass a database
connection string and mapping sourceconnection string and mapping source
 ObjectContextObjectContext propertiesproperties
ConnectionConnection – the– the SqlConnectionSqlConnection to be usedto be used
CommandTimeoutCommandTimeout – timeout for database SQL– timeout for database SQL
commands executioncommands execution
All entity classes (tables) are listed as propertiesAll entity classes (tables) are listed as properties
 e.g.e.g. ObjectSet<Order>ObjectSet<Order> OrdersOrders {{ get;get; }}
26
NorthwindEntities northwind = new NorthwindEntities();NorthwindEntities northwind = new NorthwindEntities();
Reading Data with LINQ QueryReading Data with LINQ Query
 Executing LINQ-to-Entities query overExecuting LINQ-to-Entities query over EFEF entity:entity:
 CustomersCustomers property in theproperty in the ObjectContextObjectContext::
27
public partial class NorthwindEntities : ObjectContextpublic partial class NorthwindEntities : ObjectContext
{{
public ObjectSet<Customer> Customerspublic ObjectSet<Customer> Customers
{{
get { … }get { … }
}}
}}
NorthwindEntities context = new NorthwindEntities();NorthwindEntities context = new NorthwindEntities();
var customers =var customers =
from c in context.Customersfrom c in context.Customers
where c.City == "London"where c.City == "London"
select c;select c;
The query will be executes asThe query will be executes as
SQL command in theSQL command in the
databasedatabase
Logging the Native SQL QueriesLogging the Native SQL Queries
 To print the native database SQL commandsTo print the native database SQL commands
executed on the server use the following:executed on the server use the following:
28
var query = context.Countries;var query = context.Countries;
Console.WriteLine((query as ObjectQuery).ToTraceString());Console.WriteLine((query as ObjectQuery).ToTraceString());
 This will print the SQL native query executedThis will print the SQL native query executed
at the database server to select theat the database server to select the CountriesCountries
Can be printed to file usingCan be printed to file using StreamWriterStreamWriter classclass
instead ofinstead of ConsoleConsole classclass
Retrieving Data withRetrieving Data with
LINQ to EntitiesLINQ to Entities
Live DemoLive Demo
Creating New DataCreating New Data
 To create a new database row use the methodTo create a new database row use the method
AddObject(…)AddObject(…) of theof the correspondingcorresponding collection:collection:
30
// Create new order object// Create new order object
Order order = new Order()Order order = new Order()
{{
OrderDate = DateTime.Now, ShipName = "Titanic",OrderDate = DateTime.Now, ShipName = "Titanic",
ShippedDate = new DateTime(1912, 4, 15),ShippedDate = new DateTime(1912, 4, 15),
ShipCity = "Bottom Of The Ocean"ShipCity = "Bottom Of The Ocean"
};};
// Mark the object for inserting// Mark the object for inserting
context.Orders.AddObject(order);context.Orders.AddObject(order);
context.SaveChanges();context.SaveChanges();
This willThis will
execute an SQLexecute an SQL
INSERTINSERT
 SaveChanges()SaveChanges() method call is required tomethod call is required to
post the SQL commands to the databasepost the SQL commands to the database
Creating New Data (2)Creating New Data (2)
 Creating new row can also be done by usingCreating new row can also be done by using
thethe AddToAddTo ++ The_Entity_NameThe_Entity_Name methodmethod
directly on thedirectly on the ObjectContextObjectContext
This method is depricatedThis method is depricated
Better use the other oneBetter use the other one
31
// Mark the object for inserting// Mark the object for inserting
context.AddToOrders(order);context.AddToOrders(order);
// Post changes to database (execute SQL INSERTs)// Post changes to database (execute SQL INSERTs)
context.SaveChanges();context.SaveChanges();
Cascading InsertsCascading Inserts
 We can also add cascading entities to theWe can also add cascading entities to the
database:database:
32
Country spain = new Country();Country spain = new Country();
spain.Name = "Spain";spain.Name = "Spain";
spain.Population = "46 030 10";spain.Population = "46 030 10";
spain.Cities.Add( new City { Name = "Barcelona"} );spain.Cities.Add( new City { Name = "Barcelona"} );
spain.Cities.Add( new City { Name = "Madrid"} );spain.Cities.Add( new City { Name = "Madrid"} );
countryEntities.Countries.AddObject(countryEntities.Countries.AddObject(spainspain););
countryEntities.SaveChanges();countryEntities.SaveChanges();
 This way we don't have to add eachThis way we don't have to add each CityCity
individuallyindividually
They will be added when theThey will be added when the CountryCountry entityentity
((SpainSpain)) is inserted to the databaseis inserted to the database
Updating Existing DataUpdating Existing Data
 ObjectContextObjectContext allows modifying entityallows modifying entity
properties and persisting them in the databaseproperties and persisting them in the database
Just load an entity, modify it and callJust load an entity, modify it and call
SaveChangesSaveChanges()()
 TheThe ObjectContextObjectContext automatically tracks allautomatically tracks all
changes made on its entity objectschanges made on its entity objects
33
Order order = northwindEntities.Orders.First();Order order = northwindEntities.Orders.First();
order.OrderDate = DateTime.Now;order.OrderDate = DateTime.Now;
context.SaveChanges();context.SaveChanges();
This will execute an SQLThis will execute an SQL
SELECT to load the firstSELECT to load the first
orderorder
This willThis will
execute an SQLexecute an SQL
UPDATEUPDATE
Deleting Existing DataDeleting Existing Data
 Delete is done byDelete is done by DeleteObjectDeleteObject()() on theon the
specified entity collectionspecified entity collection
 SaveChangesSaveChanges()() method performs the deletemethod performs the delete
action in the databaseaction in the database
34
Order order = northwindEntities.Orders.First();Order order = northwindEntities.Orders.First();
// Mark the entity for deleting on the next save// Mark the entity for deleting on the next save
northwindEntities.Orders.DeleteObject(order);northwindEntities.Orders.DeleteObject(order);
northwindEntities.SaveChanges();northwindEntities.SaveChanges();
This willThis will
execute an SQLexecute an SQL
DELETEDELETE
commandcommand
CRUD Operations withCRUD Operations with
Entity FrameworkEntity Framework
Live DemoLive Demo
Executing NativeExecuting Native
SQL QueriesSQL Queries
Parameterless and ParameterizedParameterless and Parameterized
Executing Native SQL QueriesExecuting Native SQL Queries
 Executing a native SQL query in EntityExecuting a native SQL query in Entity
Framework directly in its database store:Framework directly in its database store:
 Example:Example:
 Examples are shown in SQL Server but theExamples are shown in SQL Server but the
same can be done for any other databasesame can be done for any other database
ctx.ExecuteStoreQuery<return-type>(native-SQL-query);ctx.ExecuteStoreQuery<return-type>(native-SQL-query);
string query = "SELECT count(*) FROM dbo.Customers";string query = "SELECT count(*) FROM dbo.Customers";
var queryResult = ctx.ExecuteStoreQuery<int>(query);var queryResult = ctx.ExecuteStoreQuery<int>(query);
int customersCount = queryResult.FirstOrDefault();int customersCount = queryResult.FirstOrDefault();
37
Executing Native SQL QueriesExecuting Native SQL Queries
(2)(2)
NorthwindEntities context = new NorthwindEntities();NorthwindEntities context = new NorthwindEntities();
string nativeSQLQuery =string nativeSQLQuery =
"SELECT FirstName + ' ' + LastName " +"SELECT FirstName + ' ' + LastName " +
"FROM dbo.Employees " +"FROM dbo.Employees " +
"WHERE Country = {0} AND City = {1}";"WHERE Country = {0} AND City = {1}";
object[] parameters = { country, city };object[] parameters = { country, city };
var employees = context.ExecuteStoreQuery<string>(var employees = context.ExecuteStoreQuery<string>(
nativeSQLQuery, parameters);nativeSQLQuery, parameters);
foreach (var emp in employees)foreach (var emp in employees)
{{
Console.WriteLine(emp);Console.WriteLine(emp);
}}
 Native SQL queries can also be parameterized:Native SQL queries can also be parameterized:
38
Executing NativeExecuting Native
SQL QueriesSQL Queries
Live DemoLive Demo
The N+1 Query ProblemThe N+1 Query Problem
What is the N+1 Query Problem and How to Avoid It?What is the N+1 Query Problem and How to Avoid It?
The N+1 Query ProblemThe N+1 Query Problem
 What is theWhat is the N+1 Query ProblemN+1 Query Problem??
Imagine a database that contains tablesImagine a database that contains tables
CustomersCustomers andand OrdersOrders
 A customer has multiple orders (one-to-manyA customer has multiple orders (one-to-many
relationship)relationship)
We want to print eachWe want to print each CustomerCustomer and itsand its OrdersOrders::
foreach (var cust in context.Customers)foreach (var cust in context.Customers)
{{
Console.WriteLine(cust.CompanyName + "nOrders:");Console.WriteLine(cust.CompanyName + "nOrders:");
foreach (var order in cust.Orders)foreach (var order in cust.Orders)
{{
Console.WriteLine("{0}", order.OrderID);Console.WriteLine("{0}", order.OrderID);
}}
}}
41
The N+1 Query Problem (2)The N+1 Query Problem (2)
foreach (var cust in context.Customers)foreach (var cust in context.Customers)
{{
Console.WriteLine(cust.CompanyName + "nOrders:");Console.WriteLine(cust.CompanyName + "nOrders:");
foreach (var order in cust.Orders)foreach (var order in cust.Orders)
{{
Console.WriteLine("{0}", order.OrderID);Console.WriteLine("{0}", order.OrderID);
}}
}}
A single query to retrieve the countriesA single query to retrieve the countries
Additional N queries to retrieveAdditional N queries to retrieve
the cities in each countrythe cities in each country
 Imagine we have 100 countries in the databaseImagine we have 100 countries in the database
That's 101 SQL queriesThat's 101 SQL queries  very slow!very slow!
We could do the same with a single SQL queryWe could do the same with a single SQL query
 This code will execute N+1 DB queries:This code will execute N+1 DB queries:
42
Solution to the N+1 QuerySolution to the N+1 Query
ProblemProblem
 Fortunately there is an easy way in EF to avoidFortunately there is an easy way in EF to avoid
the N+1 query problemthe N+1 query problem
43
foreach (var country inforeach (var country in
countriesEntities.Countries.Include("Cities"))countriesEntities.Countries.Include("Cities"))
{{
foreach (var city in country.Cities)foreach (var city in country.Cities)
{{
Console.WriteLine(" {0}", city.CityName);Console.WriteLine(" {0}", city.CityName);
}}
}}
UsingUsing Include(…)Include(…) method only one SQLmethod only one SQL
query with join is made to get the childquery with join is made to get the child
entitiesentities
No additional SQL queries areNo additional SQL queries are
made here for the child entitiesmade here for the child entities
Solution to the N+1Solution to the N+1
Query ProblemQuery Problem
Live DemoLive Demo
Joining andJoining and
GroupingTablesGroupingTables
Join and Group Using LINQJoin and Group Using LINQ
Joining Tables in EFJoining Tables in EF
 InIn EFEF we can join tables inwe can join tables in LINQLINQ or by usingor by using
extension methods onextension methods on IEnumerable<T>IEnumerable<T>
The same way like when joining collectionsThe same way like when joining collections
var custSuppl =var custSuppl =
from customer in northwindEntities.Customersfrom customer in northwindEntities.Customers
join supplier in northwindEntities.Suppliersjoin supplier in northwindEntities.Suppliers
on customer.Country equals supplier.Countryon customer.Country equals supplier.Country
select new {select new {
CustomerName = customer.CompanyName,CustomerName = customer.CompanyName,
Supplier = supplier.CompanyName,Supplier = supplier.CompanyName,
Country = customer.CountryCountry = customer.Country
};};
var custSuppl =var custSuppl =
from customer in northwindEntities.Customersfrom customer in northwindEntities.Customers
join supplier in northwindEntities.Suppliersjoin supplier in northwindEntities.Suppliers
on customer.Country equals supplier.Countryon customer.Country equals supplier.Country
select new {select new {
CustomerName = customer.CompanyName,CustomerName = customer.CompanyName,
Supplier = supplier.CompanyName,Supplier = supplier.CompanyName,
Country = customer.CountryCountry = customer.Country
};};
northwindEntities.Customers.northwindEntities.Customers.
Join(northwindEntities.Suppliers,Join(northwindEntities.Suppliers,
(c=>c.Country), (s=>s.Country), (c,s)=>(c=>c.Country), (s=>s.Country), (c,s)=>
new {Customer = c.CompanyName, Supplier =new {Customer = c.CompanyName, Supplier =
s.CompanyName, Country = c.Country });s.CompanyName, Country = c.Country });
northwindEntities.Customers.northwindEntities.Customers.
Join(northwindEntities.Suppliers,Join(northwindEntities.Suppliers,
(c=>c.Country), (s=>s.Country), (c,s)=>(c=>c.Country), (s=>s.Country), (c,s)=>
new {Customer = c.CompanyName, Supplier =new {Customer = c.CompanyName, Supplier =
s.CompanyName, Country = c.Country });s.CompanyName, Country = c.Country });
46
Grouping Tables in EFGrouping Tables in EF
 Grouping also can be done by LINQGrouping also can be done by LINQ
The same ways as with collections in LINQThe same ways as with collections in LINQ
 Grouping with LINQ:Grouping with LINQ:
 Grouping with extension methods:Grouping with extension methods:
var groupedCustomers =var groupedCustomers =
from customer in northwindEntities.Customersfrom customer in northwindEntities.Customers
group customer by Customer.Country;group customer by Customer.Country;
var groupedCustomers =var groupedCustomers =
northwindEntities.Customers.GroupBy(northwindEntities.Customers.GroupBy(
customer => customer.Country);customer => customer.Country);
47
Joining andJoining and
GroupingTablesGroupingTables
Live DemoLive Demo
Attaching andAttaching and
Detaching ObjectsDetaching Objects
Attaching and DetachingAttaching and Detaching
ObjectsObjects
 In Entity Framework, objects can be attachedIn Entity Framework, objects can be attached
to or detached from an object contextto or detached from an object context
 AttachedAttached objects are tracked and managed byobjects are tracked and managed by
thethe ObjectContextObjectContext
SaveChanges()SaveChanges() persists all changes in DBpersists all changes in DB
 DetachedDetached objects are not referenced by theobjects are not referenced by the
ObjectContextObjectContext
Behave like a normal objects, like all others,Behave like a normal objects, like all others,
which are not related to EFwhich are not related to EF
50
Attaching Detached ObjectsAttaching Detached Objects
 When a query is executed inside anWhen a query is executed inside an
ObjectContextObjectContext, the returned objects are, the returned objects are
automatically attached to itautomatically attached to it
 When a context is destroyed, all objects in itWhen a context is destroyed, all objects in it
are automatically detachedare automatically detached
E.g. in Web applications between the requestsE.g. in Web applications between the requests
 You might late attach to a new context objectsYou might late attach to a new context objects
that have been previously detachedthat have been previously detached
51
Detaching ObjectsDetaching Objects
 When an object is detached?When an object is detached?
When we obtain the object from anWhen we obtain the object from an
ObjectContextObjectContext and theand the DisposeDispose itit
Manually: by callingManually: by calling DetachDetach(…) method(…) method
Product GetProduct(int id)Product GetProduct(int id)
{{
using (NorthwindEntities northwindEntities =using (NorthwindEntities northwindEntities =
new NorthwindEntities())new NorthwindEntities())
{{
return northwindEntities.Products.First(return northwindEntities.Products.First(
p => p.ProductID == id);p => p.ProductID == id);
}}
}}
52
Now the returned product isNow the returned product is
detacheddetached
Attaching ObjectsAttaching Objects
 When we want to update a detached object weWhen we want to update a detached object we
need to reattach it and the update itneed to reattach it and the update it
Done by theDone by the Attach(…)Attach(…) method of the contextmethod of the context
void UpdatePrice(Product product, decimal newPrice)void UpdatePrice(Product product, decimal newPrice)
{{
using (NorthwindEntities northwindEntities =using (NorthwindEntities northwindEntities =
new NorthwindEntities())new NorthwindEntities())
{{
northwindEntities.Products.Attach(product);northwindEntities.Products.Attach(product);
product.UnitPrice = newPrice;product.UnitPrice = newPrice;
northwindEntities.SaveChanges();northwindEntities.SaveChanges();
}}
}}
53
Attaching andAttaching and
Detaching ObjectsDetaching Objects
Live DemoLive Demo
UsingTransactions in EFUsingTransactions in EF
Just Use theJust Use the TransactionScopeTransactionScope ClassClass
Using Transactions in EFUsing Transactions in EF
 To perform transactional logic, just use theTo perform transactional logic, just use the
TransactionScopeTransactionScope classclass
You may need to add reference toYou may need to add reference to
System.Transactions.dllSystem.Transactions.dll
using (TransactionScope scope = new TransactionScope())using (TransactionScope scope = new TransactionScope())
{{
NorthwindEntities context = new NorthwindEntities();NorthwindEntities context = new NorthwindEntities();
// Perform a series of changes in the context// Perform a series of changes in the context
context.SaveChanges();context.SaveChanges();
scope.Complete();scope.Complete();
}}
56
Transactions in EFTransactions in EF
Live DemoLive Demo
Questions?
Entity FrameworkEntity Framework
ExercisesExercises
1.1. Using the Visual Studio Entity Framework designerUsing the Visual Studio Entity Framework designer
create acreate a ObjectContextObjectContext for thefor the NorthwindNorthwind
databasedatabase
2.2. Create a DAO class with static methods whichCreate a DAO class with static methods which
provide functionality for inserting, modifying andprovide functionality for inserting, modifying and
deleting customers. Write a testing class.deleting customers. Write a testing class.
3.3. Write a method that finds all customers who haveWrite a method that finds all customers who have
orders made in 1997 and shipped to Canada.orders made in 1997 and shipped to Canada.
4.4. Implement previous by using native SQL query andImplement previous by using native SQL query and
executing it through theexecuting it through the ObjectContextObjectContext..
5.5. Write a method that finds all the sales by specifiedWrite a method that finds all the sales by specified
region and period (start / end dates).region and period (start / end dates).
Exercises (2)Exercises (2)
6.6. Create a database calledCreate a database called NorthwindTwinNorthwindTwin with thewith the
same structure assame structure as NorthwindNorthwind using the features fromusing the features from
ObjectContextObjectContext. Find for the API for schema. Find for the API for schema
generation in MSDN or in Google.generation in MSDN or in Google.
7.7. Try to open two different data contexts and performTry to open two different data contexts and perform
concurrent changes on the same records. What willconcurrent changes on the same records. What will
happen athappen at SaveChanges()SaveChanges()? How to deal with it?? How to deal with it?
8.8. By inheriting theBy inheriting the EmployeeEmployee entity class create a classentity class create a class
which allows employees to access theirwhich allows employees to access their
corresponding territories as property of typecorresponding territories as property of type
EntitySet<T>EntitySet<T>..
Exercises (3)Exercises (3)
9.9. Create a method that places a new order in theCreate a method that places a new order in the
NorthwindNorthwind database. The order should containdatabase. The order should contain
several order items. Use transaction to ensure theseveral order items. Use transaction to ensure the
data consistency.data consistency.
10.10. Create a stored procedures in theCreate a stored procedures in the NorthwindNorthwind
database for finding the total incomes for givendatabase for finding the total incomes for given
supplier name and period (start date, end date).supplier name and period (start date, end date).
Implement a C# method that calls the storedImplement a C# method that calls the stored
procedure and returns the retuned record set.procedure and returns the retuned record set.
61
Exercises (4)Exercises (4)
11.11. Create a database holding users and groups. CreateCreate a database holding users and groups. Create
a transactional EF based method that creates ana transactional EF based method that creates an
user and puts it in a group "Admins". In case theuser and puts it in a group "Admins". In case the
group "Admins" do not exist, create the group in thegroup "Admins" do not exist, create the group in the
same transaction. If some of the operations fail (e.g.same transaction. If some of the operations fail (e.g.
the username already exist), cancel the entirethe username already exist), cancel the entire
transaction.transaction.
62

Weitere ähnliche Inhalte

Was ist angesagt?

SQL Complete Tutorial. All Topics Covered
SQL Complete Tutorial. All Topics CoveredSQL Complete Tutorial. All Topics Covered
SQL Complete Tutorial. All Topics CoveredDanish Mehraj
 
JavaScript: Operators and Expressions
JavaScript: Operators and ExpressionsJavaScript: Operators and Expressions
JavaScript: Operators and ExpressionsLearnNowOnline
 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web APIhabib_786
 
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Edureka!
 
ORM: Object-relational mapping
ORM: Object-relational mappingORM: Object-relational mapping
ORM: Object-relational mappingAbhilash M A
 
Solid NodeJS with TypeScript, Jest & NestJS
Solid NodeJS with TypeScript, Jest & NestJSSolid NodeJS with TypeScript, Jest & NestJS
Solid NodeJS with TypeScript, Jest & NestJSRafael Casuso Romate
 
REST API and CRUD
REST API and CRUDREST API and CRUD
REST API and CRUDPrem Sanil
 
ASP.NET MVC Presentation
ASP.NET MVC PresentationASP.NET MVC Presentation
ASP.NET MVC Presentationivpol
 
ASP.NET Core MVC + Web API with Overview
ASP.NET Core MVC + Web API with OverviewASP.NET Core MVC + Web API with Overview
ASP.NET Core MVC + Web API with OverviewShahed Chowdhuri
 
Java Networking
Java NetworkingJava Networking
Java NetworkingSunil OS
 

Was ist angesagt? (20)

Completable future
Completable futureCompletable future
Completable future
 
SQL Complete Tutorial. All Topics Covered
SQL Complete Tutorial. All Topics CoveredSQL Complete Tutorial. All Topics Covered
SQL Complete Tutorial. All Topics Covered
 
ADO.NET
ADO.NETADO.NET
ADO.NET
 
JavaScript: Operators and Expressions
JavaScript: Operators and ExpressionsJavaScript: Operators and Expressions
JavaScript: Operators and Expressions
 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web API
 
ADO .Net
ADO .Net ADO .Net
ADO .Net
 
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
 
Java 8 Lambda and Streams
Java 8 Lambda and StreamsJava 8 Lambda and Streams
Java 8 Lambda and Streams
 
ORM: Object-relational mapping
ORM: Object-relational mappingORM: Object-relational mapping
ORM: Object-relational mapping
 
Enumeration in c#
Enumeration in c#Enumeration in c#
Enumeration in c#
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
 
Solid NodeJS with TypeScript, Jest & NestJS
Solid NodeJS with TypeScript, Jest & NestJSSolid NodeJS with TypeScript, Jest & NestJS
Solid NodeJS with TypeScript, Jest & NestJS
 
Asp.net.
Asp.net.Asp.net.
Asp.net.
 
REST API and CRUD
REST API and CRUDREST API and CRUD
REST API and CRUD
 
ASP.NET MVC Presentation
ASP.NET MVC PresentationASP.NET MVC Presentation
ASP.NET MVC Presentation
 
ASP.NET Core MVC + Web API with Overview
ASP.NET Core MVC + Web API with OverviewASP.NET Core MVC + Web API with Overview
ASP.NET Core MVC + Web API with Overview
 
Web api
Web apiWeb api
Web api
 
Linq
LinqLinq
Linq
 
Java Networking
Java NetworkingJava Networking
Java Networking
 
Servlets
ServletsServlets
Servlets
 

Ähnlich wie ADO.NET Entity Framework

Entity Framework v1 and v2
Entity Framework v1 and v2Entity Framework v1 and v2
Entity Framework v1 and v2Eric Nelson
 
Entity Framework V1 and V2
Entity Framework V1 and V2Entity Framework V1 and V2
Entity Framework V1 and V2ukdpe
 
Entity Framework Overview
Entity Framework OverviewEntity Framework Overview
Entity Framework OverviewEric Nelson
 
Entity Framework Overview
Entity Framework OverviewEntity Framework Overview
Entity Framework Overviewukdpe
 
Net Framework Overview
Net Framework OverviewNet Framework Overview
Net Framework OverviewLuis Goldster
 
Nakov dot net-framework-overview-english
Nakov dot net-framework-overview-englishNakov dot net-framework-overview-english
Nakov dot net-framework-overview-englishsrivathsan.10
 
.NET Framework Overview
.NET Framework Overview.NET Framework Overview
.NET Framework OverviewDoncho Minkov
 
NHibernate for .NET
NHibernate for .NETNHibernate for .NET
NHibernate for .NETGuo Albert
 
LINQ to Relational in Visual Studio 2008 SP1
LINQ to Relational in Visual Studio 2008 SP1LINQ to Relational in Visual Studio 2008 SP1
LINQ to Relational in Visual Studio 2008 SP1ukdpe
 
Using entity framework core in .net
Using entity framework core in .netUsing entity framework core in .net
Using entity framework core in .netSophie Obomighie
 
NHibernate for .NET
NHibernate for .NETNHibernate for .NET
NHibernate for .NETguest1e1f73
 
DotNet Introduction
DotNet IntroductionDotNet Introduction
DotNet IntroductionWei Sun
 
Dotnetintroduce 100324201546-phpapp02
Dotnetintroduce 100324201546-phpapp02Dotnetintroduce 100324201546-phpapp02
Dotnetintroduce 100324201546-phpapp02Wei Sun
 
Building N Tier Applications With Entity Framework Services 2010
Building N Tier Applications With Entity Framework Services 2010Building N Tier Applications With Entity Framework Services 2010
Building N Tier Applications With Entity Framework Services 2010David McCarter
 
.NET Overview
.NET Overview.NET Overview
.NET OverviewGreg Sohl
 
Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)David McCarter
 
Hibernate training at HarshithaTechnologySolutions @ Nizampet
Hibernate training at HarshithaTechnologySolutions @ NizampetHibernate training at HarshithaTechnologySolutions @ Nizampet
Hibernate training at HarshithaTechnologySolutions @ NizampetJayarajus
 

Ähnlich wie ADO.NET Entity Framework (20)

Entity Framework v1 and v2
Entity Framework v1 and v2Entity Framework v1 and v2
Entity Framework v1 and v2
 
Entity Framework V1 and V2
Entity Framework V1 and V2Entity Framework V1 and V2
Entity Framework V1 and V2
 
Entity Framework Overview
Entity Framework OverviewEntity Framework Overview
Entity Framework Overview
 
Entity Framework
Entity FrameworkEntity Framework
Entity Framework
 
Entity Framework Overview
Entity Framework OverviewEntity Framework Overview
Entity Framework Overview
 
Net Framework Overview
Net Framework OverviewNet Framework Overview
Net Framework Overview
 
SynapseIndia dotnet framework library
SynapseIndia  dotnet framework librarySynapseIndia  dotnet framework library
SynapseIndia dotnet framework library
 
Nakov dot net-framework-overview-english
Nakov dot net-framework-overview-englishNakov dot net-framework-overview-english
Nakov dot net-framework-overview-english
 
Entity framework
Entity frameworkEntity framework
Entity framework
 
.NET Framework Overview
.NET Framework Overview.NET Framework Overview
.NET Framework Overview
 
NHibernate for .NET
NHibernate for .NETNHibernate for .NET
NHibernate for .NET
 
LINQ to Relational in Visual Studio 2008 SP1
LINQ to Relational in Visual Studio 2008 SP1LINQ to Relational in Visual Studio 2008 SP1
LINQ to Relational in Visual Studio 2008 SP1
 
Using entity framework core in .net
Using entity framework core in .netUsing entity framework core in .net
Using entity framework core in .net
 
NHibernate for .NET
NHibernate for .NETNHibernate for .NET
NHibernate for .NET
 
DotNet Introduction
DotNet IntroductionDotNet Introduction
DotNet Introduction
 
Dotnetintroduce 100324201546-phpapp02
Dotnetintroduce 100324201546-phpapp02Dotnetintroduce 100324201546-phpapp02
Dotnetintroduce 100324201546-phpapp02
 
Building N Tier Applications With Entity Framework Services 2010
Building N Tier Applications With Entity Framework Services 2010Building N Tier Applications With Entity Framework Services 2010
Building N Tier Applications With Entity Framework Services 2010
 
.NET Overview
.NET Overview.NET Overview
.NET Overview
 
Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)
 
Hibernate training at HarshithaTechnologySolutions @ Nizampet
Hibernate training at HarshithaTechnologySolutions @ NizampetHibernate training at HarshithaTechnologySolutions @ Nizampet
Hibernate training at HarshithaTechnologySolutions @ Nizampet
 

Mehr von Doncho Minkov

Mehr von Doncho Minkov (20)

Web Design Concepts
Web Design ConceptsWeb Design Concepts
Web Design Concepts
 
Web design Tools
Web design ToolsWeb design Tools
Web design Tools
 
HTML 5
HTML 5HTML 5
HTML 5
 
HTML 5 Tables and Forms
HTML 5 Tables and FormsHTML 5 Tables and Forms
HTML 5 Tables and Forms
 
CSS Overview
CSS OverviewCSS Overview
CSS Overview
 
CSS Presentation
CSS PresentationCSS Presentation
CSS Presentation
 
CSS Layout
CSS LayoutCSS Layout
CSS Layout
 
CSS 3
CSS 3CSS 3
CSS 3
 
Adobe Photoshop
Adobe PhotoshopAdobe Photoshop
Adobe Photoshop
 
Slice and Dice
Slice and DiceSlice and Dice
Slice and Dice
 
Introduction to XAML and WPF
Introduction to XAML and WPFIntroduction to XAML and WPF
Introduction to XAML and WPF
 
WPF Layout Containers
WPF Layout ContainersWPF Layout Containers
WPF Layout Containers
 
WPF Controls
WPF ControlsWPF Controls
WPF Controls
 
WPF Templating and Styling
WPF Templating and StylingWPF Templating and Styling
WPF Templating and Styling
 
WPF Graphics and Animations
WPF Graphics and AnimationsWPF Graphics and Animations
WPF Graphics and Animations
 
Simple Data Binding
Simple Data BindingSimple Data Binding
Simple Data Binding
 
Complex Data Binding
Complex Data BindingComplex Data Binding
Complex Data Binding
 
WPF Concepts
WPF ConceptsWPF Concepts
WPF Concepts
 
Model View ViewModel
Model View ViewModelModel View ViewModel
Model View ViewModel
 
WPF and Databases
WPF and DatabasesWPF and Databases
WPF and Databases
 

Kürzlich hochgeladen

From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 

Kürzlich hochgeladen (20)

From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 

ADO.NET Entity Framework

  • 1. ADO.NET EntityADO.NET Entity FrameworkFramework ORM Concepts, ADO.NET EntityORM Concepts, ADO.NET Entity Framework (EF),Framework (EF), ObjectContextObjectContext Doncho MinkovDoncho Minkov Telerik School AcademyTelerik School Academy schoolacademy.telerik.comschoolacademy.telerik.com Technical TrainerTechnical Trainer http://www.minkov.ithttp://www.minkov.it
  • 2. Table of ContentsTable of Contents  ORM Technologies – Basic ConceptsORM Technologies – Basic Concepts  Entity FrameworkEntity Framework OverviewOverview Printing the native SQL queriesPrinting the native SQL queries LINQ ComponentsLINQ Components Entity FilesEntity Files The Visual Studio DesignerThe Visual Studio Designer ObjectContextObjectContext Class and CRUD OperationsClass and CRUD Operations 2
  • 3. Table of Contents (2)Table of Contents (2)  Executing Native SQL QueriesExecuting Native SQL Queries Paramerterless QueriesParamerterless Queries Parameterized QueriesParameterized Queries  The N+1 Query ProblemThe N+1 Query Problem  Joining and Grouping EntitiesJoining and Grouping Entities  Attaching and Detaching ObjectsAttaching and Detaching Objects 3
  • 4. Introduction to ORMIntroduction to ORM Object-Relational Mapping (ORM)TechnologiesObject-Relational Mapping (ORM)Technologies
  • 5. ORM TechnologiesORM Technologies  Object-Relational Mapping (ORM)Object-Relational Mapping (ORM) is ais a programming technique for automaticprogramming technique for automatic mapping and converting datamapping and converting data Between relational database tables and object-Between relational database tables and object- oriented classes and objectsoriented classes and objects  ORM creates a “virtual object database“ORM creates a “virtual object database“ Which can be used from within theWhich can be used from within the programming language, e.g. C# or Javaprogramming language, e.g. C# or Java  ORM frameworksORM frameworks automate the ORM processautomate the ORM process A.k.a.A.k.a. object-relational persistence frameworksobject-relational persistence frameworks 5
  • 6. ORM FrameworksORM Frameworks  ORMORM frameworksframeworks typically provide thetypically provide the following functionality:following functionality: Creating object model by database schemaCreating object model by database schema Creating database schema by object modelCreating database schema by object model Querying data by object-oriented APIQuerying data by object-oriented API Data manipulation operationsData manipulation operations  CRUDCRUD – create, retrieve, update, delete– create, retrieve, update, delete  ORMORM frameworksframeworks automatically generate SQLautomatically generate SQL to perform the requested data operationsto perform the requested data operations 6
  • 7. ORM Mapping – ExampleORM Mapping – Example  Database and Entities mapping diagrams for aDatabase and Entities mapping diagrams for a subset of thesubset of the NorthwindNorthwind databasedatabase 7 RelationalRelational databasedatabase schemaschema ORMORM Entities (C#Entities (C# Classes)Classes) ORMORM FrameworFramewor kk
  • 8. ORM AdvantagesORM Advantages  Object-relational mapping advantagesObject-relational mapping advantages Developer productivityDeveloper productivity  Writing less codeWriting less code Abstract from differences between object andAbstract from differences between object and relational worldrelational world  Complexity hidden within ORMComplexity hidden within ORM Manageability of the CRUD operations forManageability of the CRUD operations for complex relationshipscomplex relationships Easier maintainabilityEasier maintainability 8
  • 9. Approaches to ORMApproaches to ORM  Template-based code generation vs. entityTemplate-based code generation vs. entity classes mappingsclasses mappings  SQL generation (design time / runtime) vs.SQL generation (design time / runtime) vs. mapping existing SQLmapping existing SQL  Entity classes representationEntity classes representation Entities are just POCO (Plain Old C# Objects)Entities are just POCO (Plain Old C# Objects) Entities implementEntities implement specialspecial IPersistentIPersistent interface or extendinterface or extend PersistentBasePersistentBase classclass  Configuring mappingsConfiguring mappings DB schema data vs. XML vs. annotationsDB schema data vs. XML vs. annotations 9
  • 10. Object Persistence FrameworksObject Persistence Frameworks  Code generation toolsCode generation tools Generate C#, XML and other filesGenerate C#, XML and other files Source code is compiled and used as APISource code is compiled and used as API Can be highly customizedCan be highly customized  Object-relational mapping toolsObject-relational mapping tools Mappings are described in XML files or built inMappings are described in XML files or built in the classes as attributesthe classes as attributes No source code generationNo source code generation Use of single standard APIUse of single standard API 10
  • 11. ORM Frameworks in .NETORM Frameworks in .NET  Built-in ORM tools in .NET Framework and VSBuilt-in ORM tools in .NET Framework and VS ADO.NET Entity FrameworkADO.NET Entity Framework LINQ-to-SQLLINQ-to-SQL Both combine entity class mappings and codeBoth combine entity class mappings and code generation, SQL is generated at runtimegeneration, SQL is generated at runtime  Third party ORM toolsThird party ORM tools NHibernateNHibernate – the old daddy of ORM– the old daddy of ORM Telerik OpenAccess ORMTelerik OpenAccess ORM 11
  • 12. ADO.NET Entity FrameworkADO.NET Entity Framework Object Relation Persistence FrameworkObject Relation Persistence Framework
  • 13. Overview of ADO.NET EFOverview of ADO.NET EF  Entity Framework (EF)Entity Framework (EF) is a standard ORMis a standard ORM framework, part of .NETframework, part of .NET Provides a run-time infrastructure for managingProvides a run-time infrastructure for managing SQL-based database data as .NET objectsSQL-based database data as .NET objects  The relational database schema is mapped toThe relational database schema is mapped to an object model (classes and associations)an object model (classes and associations) Visual Studio has built-in tools for generatingVisual Studio has built-in tools for generating Entity FrameworkEntity Framework SQL data mappingsSQL data mappings  Data mappings consist of C# classes and XMLData mappings consist of C# classes and XML A standard data manipulation API is providedA standard data manipulation API is provided 13
  • 14. Overview of ADO.NET EF (2)Overview of ADO.NET EF (2)  Entity FrameworkEntity Framework provides an applicationprovides an application programming interface (API)programming interface (API) For accessing data stored in database serversFor accessing data stored in database servers Built on the top of ADO.NET and LINQBuilt on the top of ADO.NET and LINQ  LINQ to EntitiesLINQ to Entities is Microsoft’s entry-levelis Microsoft’s entry-level LINQ-enabled ORM implementation forLINQ-enabled ORM implementation for database serversdatabase servers Works with SQL Server and SQL Server ExpressWorks with SQL Server and SQL Server Express Could work with MySQL, SQLite, Oracle, etc.Could work with MySQL, SQLite, Oracle, etc. Maps tables and one-to-many and many-to-Maps tables and one-to-many and many-to- many relationshipsmany relationships 14
  • 15. Entity Data ModelEntity Data Model  TheThe Entity Data Model (EDM)Entity Data Model (EDM) is a schemais a schema language for entities, consisting of:language for entities, consisting of: Conceptual model (CSDL)Conceptual model (CSDL) Mapping (MSL)Mapping (MSL) Storage Model (SSDL)Storage Model (SSDL) 15
  • 16. Entity Framework ArchitectureEntity Framework Architecture 16
  • 17. Entity Framework FeaturesEntity Framework Features  Entity Framework (EF)Entity Framework (EF) standard features:standard features: Maps tables, views, stored procedures andMaps tables, views, stored procedures and functions as .NET objectsfunctions as .NET objects Provides LINQ-based data queriesProvides LINQ-based data queries  Executed asExecuted as SQLSQL SELECTsSELECTs on the database serveron the database server CRUD operations –CRUD operations – CreateCreate//ReadRead//UpdateUpdate//DeleteDelete Create compiled queries – for executing theCreate compiled queries – for executing the same parameterized query multiple timessame parameterized query multiple times Creating or deleting the database schemaCreating or deleting the database schema 17
  • 18. Entity Framework LifecycleEntity Framework Lifecycle  When the application startsWhen the application starts EFEF translates into SQL the language-integratedtranslates into SQL the language-integrated queries in the object modelqueries in the object model Sends them to the database for later executionSends them to the database for later execution 18
  • 19. Entity Framework Lifecycle (2)Entity Framework Lifecycle (2)  When the database returns the resultsWhen the database returns the results Entity FrameworkEntity Framework translates the database rowstranslates the database rows back to .NET objectsback to .NET objects  The database server is transparent, hiddenThe database server is transparent, hidden behind the APIbehind the API  LINQ is executed overLINQ is executed over IQueryable<T>IQueryable<T>  At compile time a query expression tree isAt compile time a query expression tree is emittedemitted  At runtime SQL is generated and executedAt runtime SQL is generated and executed 19
  • 20. EF ComponentsEF Components  TheThe ObjectContextObjectContext classclass ObjectContextObjectContext holds the database connectionholds the database connection and the entity classesand the entity classes Provides LINQ-based data accessProvides LINQ-based data access Implements identity tracking, change tracking,Implements identity tracking, change tracking, and API for CRUD operationsand API for CRUD operations  Entity classesEntity classes Each database table is typically mapped to aEach database table is typically mapped to a single entity class (C# class)single entity class (C# class) 20
  • 21. EF Components (2)EF Components (2)  AssociationsAssociations An association is a primary key / foreign keyAn association is a primary key / foreign key based relationship between two entity classesbased relationship between two entity classes Allows navigation from one entity to another,Allows navigation from one entity to another, e.g.e.g. Student.CoursesStudent.Courses  Concurrency controlConcurrency control EntityEntity FrameworkFramework uses optimistic concurrencyuses optimistic concurrency control (no locking by default)control (no locking by default) Provides automatic concurrency conflictProvides automatic concurrency conflict detection and means for conflicts resolutiondetection and means for conflicts resolution 21
  • 22. LINQ to Entity Files (.LINQ to Entity Files (.edmxedmx))  Visual Studio has built-in Entity FrameworkVisual Studio has built-in Entity Framework data designer and code generatordata designer and code generator Mappings are stored inMappings are stored in .edmx.edmx files (files (EEntityntity DDataata MModelodel XXMLML)) <database>.edmx<database>.edmx is an XML fileis an XML file  Holds metadata representing the databaseHolds metadata representing the database schema (CSDL, MSL and SSDL models)schema (CSDL, MSL and SSDL models) <database>.Designer.cs<database>.Designer.cs file contains the C#file contains the C# entity classes and theentity classes and the ObjectContextObjectContext classclass  One entity class for each mapped database tableOne entity class for each mapped database table 22
  • 23. LINQ to Entity Files – ExampleLINQ to Entity Files – Example  EDMXEDMX mapping for themapping for the CategoriesCategories tabletable fromfrom NorthwindNorthwind database in SQL Serverdatabase in SQL Server 23 <EntityType Name="Categories"><EntityType Name="Categories"> <Key><Key> <PropertyRef Name="CategoryID" /><PropertyRef Name="CategoryID" /> </Key></Key> <Property Name="CategoryID" Nullable="false"<Property Name="CategoryID" Nullable="false" Type="int" StoreGeneratedPattern="Identity" />Type="int" StoreGeneratedPattern="Identity" /> <Property Name="CategoryName" Type="nvarchar"<Property Name="CategoryName" Type="nvarchar" Nullable="false" MaxLength="15" />Nullable="false" MaxLength="15" /> <Property Name="Description" Type="ntext"<Property Name="Description" Type="ntext" />/> <Property Name="Picture" Type="image" /><Property Name="Picture" Type="image" /> </EntityType></EntityType> EntityEntity classclass CategoryCategory
  • 24. The Entity FrameworkThe Entity Framework DesignerDesigner inVisual StudioinVisual Studio Live DemoLive Demo
  • 25. TheThe ObjectContextObjectContext ClassClass  TheThe ObjectContextObjectContext class is generated by theclass is generated by the Visual Studio designerVisual Studio designer  ObjectObjectContextContext provides:provides: Methods for accessing entities (object sets) andMethods for accessing entities (object sets) and creating new entities (creating new entities (AddToAddTo…… methods)methods) Ability to manipulate database data thoughAbility to manipulate database data though entity classes (read, modify, delete, insert)entity classes (read, modify, delete, insert) Easily navigate through the table relationshipsEasily navigate through the table relationships Executing LINQ queries as native SQL queriesExecuting LINQ queries as native SQL queries Create the DB schema in the database serverCreate the DB schema in the database server 25
  • 26. Using ObjectContext ClassUsing ObjectContext Class  First create instance of theFirst create instance of the ObjectContextObjectContext::  In the constructor you can pass a databaseIn the constructor you can pass a database connection string and mapping sourceconnection string and mapping source  ObjectContextObjectContext propertiesproperties ConnectionConnection – the– the SqlConnectionSqlConnection to be usedto be used CommandTimeoutCommandTimeout – timeout for database SQL– timeout for database SQL commands executioncommands execution All entity classes (tables) are listed as propertiesAll entity classes (tables) are listed as properties  e.g.e.g. ObjectSet<Order>ObjectSet<Order> OrdersOrders {{ get;get; }} 26 NorthwindEntities northwind = new NorthwindEntities();NorthwindEntities northwind = new NorthwindEntities();
  • 27. Reading Data with LINQ QueryReading Data with LINQ Query  Executing LINQ-to-Entities query overExecuting LINQ-to-Entities query over EFEF entity:entity:  CustomersCustomers property in theproperty in the ObjectContextObjectContext:: 27 public partial class NorthwindEntities : ObjectContextpublic partial class NorthwindEntities : ObjectContext {{ public ObjectSet<Customer> Customerspublic ObjectSet<Customer> Customers {{ get { … }get { … } }} }} NorthwindEntities context = new NorthwindEntities();NorthwindEntities context = new NorthwindEntities(); var customers =var customers = from c in context.Customersfrom c in context.Customers where c.City == "London"where c.City == "London" select c;select c; The query will be executes asThe query will be executes as SQL command in theSQL command in the databasedatabase
  • 28. Logging the Native SQL QueriesLogging the Native SQL Queries  To print the native database SQL commandsTo print the native database SQL commands executed on the server use the following:executed on the server use the following: 28 var query = context.Countries;var query = context.Countries; Console.WriteLine((query as ObjectQuery).ToTraceString());Console.WriteLine((query as ObjectQuery).ToTraceString());  This will print the SQL native query executedThis will print the SQL native query executed at the database server to select theat the database server to select the CountriesCountries Can be printed to file usingCan be printed to file using StreamWriterStreamWriter classclass instead ofinstead of ConsoleConsole classclass
  • 29. Retrieving Data withRetrieving Data with LINQ to EntitiesLINQ to Entities Live DemoLive Demo
  • 30. Creating New DataCreating New Data  To create a new database row use the methodTo create a new database row use the method AddObject(…)AddObject(…) of theof the correspondingcorresponding collection:collection: 30 // Create new order object// Create new order object Order order = new Order()Order order = new Order() {{ OrderDate = DateTime.Now, ShipName = "Titanic",OrderDate = DateTime.Now, ShipName = "Titanic", ShippedDate = new DateTime(1912, 4, 15),ShippedDate = new DateTime(1912, 4, 15), ShipCity = "Bottom Of The Ocean"ShipCity = "Bottom Of The Ocean" };}; // Mark the object for inserting// Mark the object for inserting context.Orders.AddObject(order);context.Orders.AddObject(order); context.SaveChanges();context.SaveChanges(); This willThis will execute an SQLexecute an SQL INSERTINSERT  SaveChanges()SaveChanges() method call is required tomethod call is required to post the SQL commands to the databasepost the SQL commands to the database
  • 31. Creating New Data (2)Creating New Data (2)  Creating new row can also be done by usingCreating new row can also be done by using thethe AddToAddTo ++ The_Entity_NameThe_Entity_Name methodmethod directly on thedirectly on the ObjectContextObjectContext This method is depricatedThis method is depricated Better use the other oneBetter use the other one 31 // Mark the object for inserting// Mark the object for inserting context.AddToOrders(order);context.AddToOrders(order); // Post changes to database (execute SQL INSERTs)// Post changes to database (execute SQL INSERTs) context.SaveChanges();context.SaveChanges();
  • 32. Cascading InsertsCascading Inserts  We can also add cascading entities to theWe can also add cascading entities to the database:database: 32 Country spain = new Country();Country spain = new Country(); spain.Name = "Spain";spain.Name = "Spain"; spain.Population = "46 030 10";spain.Population = "46 030 10"; spain.Cities.Add( new City { Name = "Barcelona"} );spain.Cities.Add( new City { Name = "Barcelona"} ); spain.Cities.Add( new City { Name = "Madrid"} );spain.Cities.Add( new City { Name = "Madrid"} ); countryEntities.Countries.AddObject(countryEntities.Countries.AddObject(spainspain);); countryEntities.SaveChanges();countryEntities.SaveChanges();  This way we don't have to add eachThis way we don't have to add each CityCity individuallyindividually They will be added when theThey will be added when the CountryCountry entityentity ((SpainSpain)) is inserted to the databaseis inserted to the database
  • 33. Updating Existing DataUpdating Existing Data  ObjectContextObjectContext allows modifying entityallows modifying entity properties and persisting them in the databaseproperties and persisting them in the database Just load an entity, modify it and callJust load an entity, modify it and call SaveChangesSaveChanges()()  TheThe ObjectContextObjectContext automatically tracks allautomatically tracks all changes made on its entity objectschanges made on its entity objects 33 Order order = northwindEntities.Orders.First();Order order = northwindEntities.Orders.First(); order.OrderDate = DateTime.Now;order.OrderDate = DateTime.Now; context.SaveChanges();context.SaveChanges(); This will execute an SQLThis will execute an SQL SELECT to load the firstSELECT to load the first orderorder This willThis will execute an SQLexecute an SQL UPDATEUPDATE
  • 34. Deleting Existing DataDeleting Existing Data  Delete is done byDelete is done by DeleteObjectDeleteObject()() on theon the specified entity collectionspecified entity collection  SaveChangesSaveChanges()() method performs the deletemethod performs the delete action in the databaseaction in the database 34 Order order = northwindEntities.Orders.First();Order order = northwindEntities.Orders.First(); // Mark the entity for deleting on the next save// Mark the entity for deleting on the next save northwindEntities.Orders.DeleteObject(order);northwindEntities.Orders.DeleteObject(order); northwindEntities.SaveChanges();northwindEntities.SaveChanges(); This willThis will execute an SQLexecute an SQL DELETEDELETE commandcommand
  • 35. CRUD Operations withCRUD Operations with Entity FrameworkEntity Framework Live DemoLive Demo
  • 36. Executing NativeExecuting Native SQL QueriesSQL Queries Parameterless and ParameterizedParameterless and Parameterized
  • 37. Executing Native SQL QueriesExecuting Native SQL Queries  Executing a native SQL query in EntityExecuting a native SQL query in Entity Framework directly in its database store:Framework directly in its database store:  Example:Example:  Examples are shown in SQL Server but theExamples are shown in SQL Server but the same can be done for any other databasesame can be done for any other database ctx.ExecuteStoreQuery<return-type>(native-SQL-query);ctx.ExecuteStoreQuery<return-type>(native-SQL-query); string query = "SELECT count(*) FROM dbo.Customers";string query = "SELECT count(*) FROM dbo.Customers"; var queryResult = ctx.ExecuteStoreQuery<int>(query);var queryResult = ctx.ExecuteStoreQuery<int>(query); int customersCount = queryResult.FirstOrDefault();int customersCount = queryResult.FirstOrDefault(); 37
  • 38. Executing Native SQL QueriesExecuting Native SQL Queries (2)(2) NorthwindEntities context = new NorthwindEntities();NorthwindEntities context = new NorthwindEntities(); string nativeSQLQuery =string nativeSQLQuery = "SELECT FirstName + ' ' + LastName " +"SELECT FirstName + ' ' + LastName " + "FROM dbo.Employees " +"FROM dbo.Employees " + "WHERE Country = {0} AND City = {1}";"WHERE Country = {0} AND City = {1}"; object[] parameters = { country, city };object[] parameters = { country, city }; var employees = context.ExecuteStoreQuery<string>(var employees = context.ExecuteStoreQuery<string>( nativeSQLQuery, parameters);nativeSQLQuery, parameters); foreach (var emp in employees)foreach (var emp in employees) {{ Console.WriteLine(emp);Console.WriteLine(emp); }}  Native SQL queries can also be parameterized:Native SQL queries can also be parameterized: 38
  • 39. Executing NativeExecuting Native SQL QueriesSQL Queries Live DemoLive Demo
  • 40. The N+1 Query ProblemThe N+1 Query Problem What is the N+1 Query Problem and How to Avoid It?What is the N+1 Query Problem and How to Avoid It?
  • 41. The N+1 Query ProblemThe N+1 Query Problem  What is theWhat is the N+1 Query ProblemN+1 Query Problem?? Imagine a database that contains tablesImagine a database that contains tables CustomersCustomers andand OrdersOrders  A customer has multiple orders (one-to-manyA customer has multiple orders (one-to-many relationship)relationship) We want to print eachWe want to print each CustomerCustomer and itsand its OrdersOrders:: foreach (var cust in context.Customers)foreach (var cust in context.Customers) {{ Console.WriteLine(cust.CompanyName + "nOrders:");Console.WriteLine(cust.CompanyName + "nOrders:"); foreach (var order in cust.Orders)foreach (var order in cust.Orders) {{ Console.WriteLine("{0}", order.OrderID);Console.WriteLine("{0}", order.OrderID); }} }} 41
  • 42. The N+1 Query Problem (2)The N+1 Query Problem (2) foreach (var cust in context.Customers)foreach (var cust in context.Customers) {{ Console.WriteLine(cust.CompanyName + "nOrders:");Console.WriteLine(cust.CompanyName + "nOrders:"); foreach (var order in cust.Orders)foreach (var order in cust.Orders) {{ Console.WriteLine("{0}", order.OrderID);Console.WriteLine("{0}", order.OrderID); }} }} A single query to retrieve the countriesA single query to retrieve the countries Additional N queries to retrieveAdditional N queries to retrieve the cities in each countrythe cities in each country  Imagine we have 100 countries in the databaseImagine we have 100 countries in the database That's 101 SQL queriesThat's 101 SQL queries  very slow!very slow! We could do the same with a single SQL queryWe could do the same with a single SQL query  This code will execute N+1 DB queries:This code will execute N+1 DB queries: 42
  • 43. Solution to the N+1 QuerySolution to the N+1 Query ProblemProblem  Fortunately there is an easy way in EF to avoidFortunately there is an easy way in EF to avoid the N+1 query problemthe N+1 query problem 43 foreach (var country inforeach (var country in countriesEntities.Countries.Include("Cities"))countriesEntities.Countries.Include("Cities")) {{ foreach (var city in country.Cities)foreach (var city in country.Cities) {{ Console.WriteLine(" {0}", city.CityName);Console.WriteLine(" {0}", city.CityName); }} }} UsingUsing Include(…)Include(…) method only one SQLmethod only one SQL query with join is made to get the childquery with join is made to get the child entitiesentities No additional SQL queries areNo additional SQL queries are made here for the child entitiesmade here for the child entities
  • 44. Solution to the N+1Solution to the N+1 Query ProblemQuery Problem Live DemoLive Demo
  • 45. Joining andJoining and GroupingTablesGroupingTables Join and Group Using LINQJoin and Group Using LINQ
  • 46. Joining Tables in EFJoining Tables in EF  InIn EFEF we can join tables inwe can join tables in LINQLINQ or by usingor by using extension methods onextension methods on IEnumerable<T>IEnumerable<T> The same way like when joining collectionsThe same way like when joining collections var custSuppl =var custSuppl = from customer in northwindEntities.Customersfrom customer in northwindEntities.Customers join supplier in northwindEntities.Suppliersjoin supplier in northwindEntities.Suppliers on customer.Country equals supplier.Countryon customer.Country equals supplier.Country select new {select new { CustomerName = customer.CompanyName,CustomerName = customer.CompanyName, Supplier = supplier.CompanyName,Supplier = supplier.CompanyName, Country = customer.CountryCountry = customer.Country };}; var custSuppl =var custSuppl = from customer in northwindEntities.Customersfrom customer in northwindEntities.Customers join supplier in northwindEntities.Suppliersjoin supplier in northwindEntities.Suppliers on customer.Country equals supplier.Countryon customer.Country equals supplier.Country select new {select new { CustomerName = customer.CompanyName,CustomerName = customer.CompanyName, Supplier = supplier.CompanyName,Supplier = supplier.CompanyName, Country = customer.CountryCountry = customer.Country };}; northwindEntities.Customers.northwindEntities.Customers. Join(northwindEntities.Suppliers,Join(northwindEntities.Suppliers, (c=>c.Country), (s=>s.Country), (c,s)=>(c=>c.Country), (s=>s.Country), (c,s)=> new {Customer = c.CompanyName, Supplier =new {Customer = c.CompanyName, Supplier = s.CompanyName, Country = c.Country });s.CompanyName, Country = c.Country }); northwindEntities.Customers.northwindEntities.Customers. Join(northwindEntities.Suppliers,Join(northwindEntities.Suppliers, (c=>c.Country), (s=>s.Country), (c,s)=>(c=>c.Country), (s=>s.Country), (c,s)=> new {Customer = c.CompanyName, Supplier =new {Customer = c.CompanyName, Supplier = s.CompanyName, Country = c.Country });s.CompanyName, Country = c.Country }); 46
  • 47. Grouping Tables in EFGrouping Tables in EF  Grouping also can be done by LINQGrouping also can be done by LINQ The same ways as with collections in LINQThe same ways as with collections in LINQ  Grouping with LINQ:Grouping with LINQ:  Grouping with extension methods:Grouping with extension methods: var groupedCustomers =var groupedCustomers = from customer in northwindEntities.Customersfrom customer in northwindEntities.Customers group customer by Customer.Country;group customer by Customer.Country; var groupedCustomers =var groupedCustomers = northwindEntities.Customers.GroupBy(northwindEntities.Customers.GroupBy( customer => customer.Country);customer => customer.Country); 47
  • 49. Attaching andAttaching and Detaching ObjectsDetaching Objects
  • 50. Attaching and DetachingAttaching and Detaching ObjectsObjects  In Entity Framework, objects can be attachedIn Entity Framework, objects can be attached to or detached from an object contextto or detached from an object context  AttachedAttached objects are tracked and managed byobjects are tracked and managed by thethe ObjectContextObjectContext SaveChanges()SaveChanges() persists all changes in DBpersists all changes in DB  DetachedDetached objects are not referenced by theobjects are not referenced by the ObjectContextObjectContext Behave like a normal objects, like all others,Behave like a normal objects, like all others, which are not related to EFwhich are not related to EF 50
  • 51. Attaching Detached ObjectsAttaching Detached Objects  When a query is executed inside anWhen a query is executed inside an ObjectContextObjectContext, the returned objects are, the returned objects are automatically attached to itautomatically attached to it  When a context is destroyed, all objects in itWhen a context is destroyed, all objects in it are automatically detachedare automatically detached E.g. in Web applications between the requestsE.g. in Web applications between the requests  You might late attach to a new context objectsYou might late attach to a new context objects that have been previously detachedthat have been previously detached 51
  • 52. Detaching ObjectsDetaching Objects  When an object is detached?When an object is detached? When we obtain the object from anWhen we obtain the object from an ObjectContextObjectContext and theand the DisposeDispose itit Manually: by callingManually: by calling DetachDetach(…) method(…) method Product GetProduct(int id)Product GetProduct(int id) {{ using (NorthwindEntities northwindEntities =using (NorthwindEntities northwindEntities = new NorthwindEntities())new NorthwindEntities()) {{ return northwindEntities.Products.First(return northwindEntities.Products.First( p => p.ProductID == id);p => p.ProductID == id); }} }} 52 Now the returned product isNow the returned product is detacheddetached
  • 53. Attaching ObjectsAttaching Objects  When we want to update a detached object weWhen we want to update a detached object we need to reattach it and the update itneed to reattach it and the update it Done by theDone by the Attach(…)Attach(…) method of the contextmethod of the context void UpdatePrice(Product product, decimal newPrice)void UpdatePrice(Product product, decimal newPrice) {{ using (NorthwindEntities northwindEntities =using (NorthwindEntities northwindEntities = new NorthwindEntities())new NorthwindEntities()) {{ northwindEntities.Products.Attach(product);northwindEntities.Products.Attach(product); product.UnitPrice = newPrice;product.UnitPrice = newPrice; northwindEntities.SaveChanges();northwindEntities.SaveChanges(); }} }} 53
  • 54. Attaching andAttaching and Detaching ObjectsDetaching Objects Live DemoLive Demo
  • 55. UsingTransactions in EFUsingTransactions in EF Just Use theJust Use the TransactionScopeTransactionScope ClassClass
  • 56. Using Transactions in EFUsing Transactions in EF  To perform transactional logic, just use theTo perform transactional logic, just use the TransactionScopeTransactionScope classclass You may need to add reference toYou may need to add reference to System.Transactions.dllSystem.Transactions.dll using (TransactionScope scope = new TransactionScope())using (TransactionScope scope = new TransactionScope()) {{ NorthwindEntities context = new NorthwindEntities();NorthwindEntities context = new NorthwindEntities(); // Perform a series of changes in the context// Perform a series of changes in the context context.SaveChanges();context.SaveChanges(); scope.Complete();scope.Complete(); }} 56
  • 57. Transactions in EFTransactions in EF Live DemoLive Demo
  • 59. ExercisesExercises 1.1. Using the Visual Studio Entity Framework designerUsing the Visual Studio Entity Framework designer create acreate a ObjectContextObjectContext for thefor the NorthwindNorthwind databasedatabase 2.2. Create a DAO class with static methods whichCreate a DAO class with static methods which provide functionality for inserting, modifying andprovide functionality for inserting, modifying and deleting customers. Write a testing class.deleting customers. Write a testing class. 3.3. Write a method that finds all customers who haveWrite a method that finds all customers who have orders made in 1997 and shipped to Canada.orders made in 1997 and shipped to Canada. 4.4. Implement previous by using native SQL query andImplement previous by using native SQL query and executing it through theexecuting it through the ObjectContextObjectContext.. 5.5. Write a method that finds all the sales by specifiedWrite a method that finds all the sales by specified region and period (start / end dates).region and period (start / end dates).
  • 60. Exercises (2)Exercises (2) 6.6. Create a database calledCreate a database called NorthwindTwinNorthwindTwin with thewith the same structure assame structure as NorthwindNorthwind using the features fromusing the features from ObjectContextObjectContext. Find for the API for schema. Find for the API for schema generation in MSDN or in Google.generation in MSDN or in Google. 7.7. Try to open two different data contexts and performTry to open two different data contexts and perform concurrent changes on the same records. What willconcurrent changes on the same records. What will happen athappen at SaveChanges()SaveChanges()? How to deal with it?? How to deal with it? 8.8. By inheriting theBy inheriting the EmployeeEmployee entity class create a classentity class create a class which allows employees to access theirwhich allows employees to access their corresponding territories as property of typecorresponding territories as property of type EntitySet<T>EntitySet<T>..
  • 61. Exercises (3)Exercises (3) 9.9. Create a method that places a new order in theCreate a method that places a new order in the NorthwindNorthwind database. The order should containdatabase. The order should contain several order items. Use transaction to ensure theseveral order items. Use transaction to ensure the data consistency.data consistency. 10.10. Create a stored procedures in theCreate a stored procedures in the NorthwindNorthwind database for finding the total incomes for givendatabase for finding the total incomes for given supplier name and period (start date, end date).supplier name and period (start date, end date). Implement a C# method that calls the storedImplement a C# method that calls the stored procedure and returns the retuned record set.procedure and returns the retuned record set. 61
  • 62. Exercises (4)Exercises (4) 11.11. Create a database holding users and groups. CreateCreate a database holding users and groups. Create a transactional EF based method that creates ana transactional EF based method that creates an user and puts it in a group "Admins". In case theuser and puts it in a group "Admins". In case the group "Admins" do not exist, create the group in thegroup "Admins" do not exist, create the group in the same transaction. If some of the operations fail (e.g.same transaction. If some of the operations fail (e.g. the username already exist), cancel the entirethe username already exist), cancel the entire transaction.transaction. 62