Download - ADO.NET Entity Framework
![Page 1: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/1.jpg)
ADO.NET ADO.NET Entity Entity
FrameworkFrameworkORM Concepts, ADO.NET ORM Concepts, ADO.NET
EntityEntityFramework (EF), Framework (EF),
ObjectContextObjectContext
Doncho MinkovDoncho Minkov
Telerik School AcademyTelerik School Academyschoolacademy.telerik.com
Technical TrainerTechnical Trainerhttp://www.minkov.it
![Page 2: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/2.jpg)
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 Class and CRUD OperationsOperations
2
![Page 3: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/3.jpg)
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
![Page 4: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/4.jpg)
Introduction to ORMIntroduction to ORMObject-Relational Mapping (ORM) Object-Relational Mapping (ORM)
TechnologiesTechnologies
![Page 5: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/5.jpg)
ORM TechnologiesORM Technologies Object-Relational Mapping (ORM)Object-Relational Mapping (ORM) is a is a
programming technique for automatic programming technique for automatic mapping and converting datamapping and converting data Between relational database tables and Between relational database tables and
object-oriented classes and objectsobject-oriented classes and objects ORM creates a “virtual object database“ ORM creates a “virtual object database“
Which can be used from within the Which 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 automate the ORM processprocess A.k.a. A.k.a. object-relational persistence object-relational persistence
frameworksframeworks5
![Page 6: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/6.jpg)
ORM FrameworksORM Frameworks ORMORM frameworksframeworks typically provide the typically provide the
following functionality:following functionality: Creating object model by database Creating object model by database
schemaschema Creating database schema by object Creating database schema by object
modelmodel 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 automatically generate SQL to perform the requested data SQL to perform the requested data operationsoperations 6
![Page 7: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/7.jpg)
ORM Mapping – ORM Mapping – ExampleExample
Database and Entities mapping Database and Entities mapping diagrams for a subset of the diagrams for a subset of the NorthwindNorthwind database database
7
Relational Relational database database schemaschema
ORM ORM Entities Entities
(C# (C# Classes)Classes)
ORMORMFramewFramew
orkork
![Page 8: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/8.jpg)
ORM AdvantagesORM Advantages Object-relational mapping Object-relational mapping
advantagesadvantages Developer productivityDeveloper productivity
Writing less codeWriting less code
Abstract from differences between Abstract from differences between object and relational worldobject and relational world Complexity hidden within ORMComplexity hidden within ORM
Manageability of the CRUD Manageability of the CRUD operations for complex relationshipsoperations for complex relationships
Easier maintainabilityEasier maintainability8
![Page 9: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/9.jpg)
Approaches to ORMApproaches to ORM Template-based code generation vs. Template-based code generation vs.
entity classes mappingsentity classes mappings SQL generation (design time / runtime) SQL generation (design time / runtime)
vs. mapping existing SQLvs. mapping existing SQL Entity classes representationEntity classes representation
Entities are just POCO (Plain Old C# Entities are just POCO (Plain Old C# Objects)Objects)
Entities implementEntities implement special special IPersistentIPersistent interface or extend interface or extend PersistentBasePersistentBase class class
Configuring mappingsConfiguring mappings DB schema data vs. XML vs. annotationsDB schema data vs. XML vs. annotations
9
![Page 10: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/10.jpg)
Object Persistence Object Persistence FrameworksFrameworks
Code generation toolsCode generation tools Generate C#, XML and other filesGenerate C#, XML and other files Source code is compiled and used Source code is compiled and used
as APIas API Can be highly customizedCan be highly customized
Object-relational mapping toolsObject-relational mapping tools Mappings are described in XML files Mappings are described in XML files
or built in the classes as attributesor built in the classes as attributes No source code generationNo source code generation Use of single standard API Use of single standard API 10
![Page 11: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/11.jpg)
ORM Frameworks ORM Frameworks in .NETin .NET
Built-in ORM tools in .NET Framework Built-in ORM tools in .NET Framework and VSand VS
ADO.NET Entity FrameworkADO.NET Entity Framework
LINQ-to-SQLLINQ-to-SQL
Both combine entity class mappings Both combine entity class mappings and code generation, SQL is generated and code generation, SQL is generated at runtimeat 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
![Page 12: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/12.jpg)
ADO.NET Entity ADO.NET Entity FrameworkFrameworkObject Relation Persistence Object Relation Persistence
FrameworkFramework
![Page 13: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/13.jpg)
Overview of ADO.NET Overview of ADO.NET EFEF
Entity Framework (EF) Entity Framework (EF) is a standard ORM is a standard ORM framework, part of .NETframework, part of .NET Provides a run-time infrastructure for Provides a run-time infrastructure for
managing SQL-based database data as .NET managing SQL-based database data as .NET objectsobjects
The relational database schema is mapped The relational database schema is mapped to an object model (classes and to an object model (classes and associations)associations) Visual Studio has built-in tools for generating Visual Studio has built-in tools for generating
Entity Framework Entity 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
![Page 14: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/14.jpg)
Overview of ADO.NET Overview of ADO.NET EF (2)EF (2)
Entity Framework Entity Framework provides an application provides an application programming interface (API)programming interface (API) For accessing data stored in database For accessing data stored in database
serversservers Built on the top of ADO.NET and LINQBuilt on the top of ADO.NET and LINQ
LINQ to Entities LINQ to Entities is Microsoft’s entry-level is Microsoft’s entry-level LINQ-enabled ORM implementation for LINQ-enabled ORM implementation for database serversdatabase servers Works with SQL Server and SQL Server Works with SQL Server and SQL Server
ExpressExpress Could work with MySQL, SQLite, Oracle, Could work with MySQL, SQLite, Oracle,
etc.etc. Maps tables and one-to-many and many-Maps tables and one-to-many and many-
to-many relationshipsto-many relationships 14
![Page 15: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/15.jpg)
Entity Data ModelEntity Data Model The The Entity Data Model (EDM)Entity Data Model (EDM) is a is a
schema language for entities, schema language for entities, consisting of:consisting of: Conceptual model (CSDL)Conceptual model (CSDL)
Mapping (MSL)Mapping (MSL)
Storage Model (SSDL)Storage Model (SSDL)
15
![Page 16: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/16.jpg)
Entity Framework Entity Framework ArchitectureArchitecture
16
![Page 17: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/17.jpg)
Entity Framework Entity Framework FeaturesFeatures
Entity Framework (EF)Entity Framework (EF) standard features: standard features: Maps tables, views, stored procedures and Maps tables, views, stored procedures and
functions as .NET objectsfunctions as .NET objects Provides LINQ-based data queriesProvides LINQ-based data queries
Executed as Executed as SQLSQL SELECTsSELECTs on the database on the database serverserver
CRUD operations – CRUD operations – CreateCreate//ReadRead//UpdateUpdate//DeleteDelete
Create compiled queries – for executing the Create 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
![Page 18: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/18.jpg)
Entity Framework Entity Framework LifecycleLifecycle
When the application startsWhen the application starts EFEF translates into SQL the translates into SQL the
language-integrated queries in the language-integrated queries in the object modelobject model
Sends them to the database for Sends them to the database for later executionlater execution
18
![Page 19: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/19.jpg)
Entity Framework Entity Framework Lifecycle (2)Lifecycle (2)
When the database returns the When the database returns the resultsresults Entity Framework Entity Framework translates the translates the
database rows back to .NET objectsdatabase rows back to .NET objects The database server is transparent, The database server is transparent,
hidden behind the APIhidden behind the API LINQ is executed over LINQ is executed over IQueryable<T>IQueryable<T>
At compile time a query expression At compile time a query expression tree is emittedtree is emitted
At runtime SQL is generated and At runtime SQL is generated and executedexecuted
19
![Page 20: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/20.jpg)
EF ComponentsEF Components The The ObjectContextObjectContext classclass
ObjectContextObjectContext holds the database holds the database connection and the entity classesconnection and the entity classes
Provides LINQ-based data accessProvides LINQ-based data access Implements identity tracking, change Implements identity tracking, change
tracking, and API for CRUD tracking, and API for CRUD operationsoperations
Entity classesEntity classes Each database table is typically Each database table is typically
mapped to a single entity class (C# mapped to a single entity class (C# class)class) 20
![Page 21: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/21.jpg)
EF Components (2)EF Components (2) AssociationsAssociations
An association is a primary key / foreign An association is a primary key / foreign key based relationship between two entity key based relationship between two entity classesclasses
Allows navigation from one entity to Allows navigation from one entity to another, e.g. another, e.g. Student.CoursesStudent.Courses
Concurrency controlConcurrency control EntityEntity FrameworkFramework uses optimistic uses optimistic
concurrency control (no locking by default)concurrency control (no locking by default) Provides automatic concurrency conflict Provides automatic concurrency conflict
detection and means for conflicts detection and means for conflicts resolutionresolution
21
![Page 22: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/22.jpg)
LINQ to Entity Files LINQ to Entity Files (.(.edmxedmx))
Visual Studio has built-in Entity Visual Studio has built-in Entity Framework data designer and code Framework data designer and code generatorgenerator Mappings are stored in Mappings are stored in .edmx.edmx files (files (EEntityntity
DDataata M Modelodel X XMLML)) <database>.edmx<database>.edmx is an XML fileis an XML file
Holds metadata representing the database Holds 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 file contains the C# entity classes and the C# entity classes and the ObjectContext ObjectContext classclass One entity class for each mapped database One entity class for each mapped database
tabletable 22
![Page 23: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/23.jpg)
LINQ to Entity Files – LINQ to Entity Files – ExampleExample
EDMXEDMX mapping for the mapping for the CategoriesCategories table table from from NorthwindNorthwind database in SQL Server database in SQL Server
23
<EntityType Name="Categories"><EntityType Name="Categories">
<Key><Key> <PropertyRef Name="CategoryID" /><PropertyRef Name="CategoryID" /> </Key></Key>
<Property Name="CategoryID" <Property Name="CategoryID" Nullable="false" Nullable="false" Type="int" Type="int" StoreGeneratedPattern="Identity" />StoreGeneratedPattern="Identity" /> <Property Name="CategoryName" <Property Name="CategoryName" Type="nvarchar" 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>
Entity Entity class class
CategorCategoryy
![Page 24: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/24.jpg)
The Entity The Entity Framework DesignerFramework Designer
in Visual Studioin Visual StudioLive DemoLive Demo
![Page 25: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/25.jpg)
The The ObjectContextObjectContext ClassClass The The ObjectContextObjectContext class is generated by the class is generated by the
Visual Studio designerVisual Studio designer ObjectObjectContextContext provides: provides:
Methods for accessing entities (object sets) Methods for accessing entities (object sets) and creating new entities (and creating new entities (AddToAddTo…… methods) methods)
Ability to manipulate database data though Ability to manipulate database data though entity classes (read, modify, delete, insert)entity classes (read, modify, delete, insert)
Easily navigate through the table Easily navigate through the table relationshipsrelationships
Executing LINQ queries as native SQL Executing LINQ queries as native SQL queriesqueries
Create the DB schema in the database serverCreate the DB schema in the database server
25
![Page 26: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/26.jpg)
Using ObjectContext Using ObjectContext ClassClass
First create instance of the First create instance of the ObjectContextObjectContext::
In the constructor you can pass a In the constructor you can pass a database connection string and mapping database connection string and mapping sourcesource
ObjectContextObjectContext properties properties ConnectionConnection – the – the SqlConnectionSqlConnection to be used to be used CommandTimeoutCommandTimeout – timeout for database SQL – timeout for database SQL
commands executioncommands execution All entity classes (tables) are listed as All entity classes (tables) are listed as
propertiesproperties e.g. e.g. ObjectSet<Order>ObjectSet<Order> OrdersOrders {{ get;get; }}
26
NorthwindEntities northwind = new NorthwindEntities northwind = new NorthwindEntities();NorthwindEntities();
![Page 27: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/27.jpg)
Reading Data with LINQ Reading Data with LINQ QueryQuery
Executing LINQ-to-Entities query over Executing LINQ-to-Entities query over EFEF entity:entity:
CustomersCustomers property in the property in the ObjectContextObjectContext::
27
public partial class NorthwindEntities : public partial class NorthwindEntities : ObjectContextObjectContext{{ public ObjectSet<Customer> Customerspublic ObjectSet<Customer> Customers { { get { … }get { … } }}}}
NorthwindEntities context = new NorthwindEntities context = new NorthwindEntities();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 The query will be executes as SQL executes as SQL command in the command in the
databasedatabase
![Page 28: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/28.jpg)
Logging the Native SQL Logging the Native SQL QueriesQueries
To print the native database SQL To print the native database SQL commands executed on the server commands executed on the server use the following:use the following:
28
var query = context.Countries;var query = context.Countries;Console.WriteLine((query as Console.WriteLine((query as ObjectQuery).ToTraceString());ObjectQuery).ToTraceString());
This will print the SQL native query This will print the SQL native query executed at the database server to executed at the database server to select the select the CountriesCountries Can be printed to file using Can be printed to file using StreamWriterStreamWriter class instead of class instead of ConsoleConsole classclass
![Page 29: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/29.jpg)
Retrieving Data Retrieving Data with LINQ to with LINQ to
EntitiesEntitiesLive DemoLive Demo
![Page 30: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/30.jpg)
Creating New DataCreating New Data To create a new database row use the method To create a new database row use the method
AddObject(…)AddObject(…) of the of the corresponding corresponding collection:collection:
30
// Create new order object// Create new order objectOrder 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 insertingcontext.Orders.AddObject(order);context.Orders.AddObject(order);context.SaveChanges();context.SaveChanges();
This will This will execute an execute an SQL INSERTSQL INSERT
SaveChanges()SaveChanges() method call is method call is required to post the SQL required to post the SQL commands to the databasecommands to the database
![Page 31: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/31.jpg)
Creating New Data (2)Creating New Data (2) Creating new row can also be done by Creating new row can also be done by
using the using the AddTo AddTo + + The_Entity_Name The_Entity_Name method directly on the method directly 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 insertingcontext.AddToOrders(order);context.AddToOrders(order);
// Post changes to database (execute SQL INSERTs)// Post changes to database (execute SQL INSERTs)context.SaveChanges();context.SaveChanges();
![Page 32: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/32.jpg)
Cascading InsertsCascading Inserts We can also add cascading We can also add cascading
entities to the database:entities to the 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 = spain.Cities.Add( new City { Name = "Barcelona"} );"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 This way we don't have to add each each CityCity individually individually They will be added when the They will be added when the CountryCountry entity ( entity (SpainSpain)) is inserted is inserted to the databaseto the database
![Page 33: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/33.jpg)
Updating Existing DataUpdating Existing Data ObjectContextObjectContext allows modifying allows modifying
entity properties and persisting entity properties and persisting them in the databasethem in the database Just load an entity, modify it and Just load an entity, modify it and
call call SaveChangesSaveChanges()() The The ObjectContextObjectContext automatically automatically
tracks all changes made on its tracks all changes made on its entity objectsentity 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 This will execute an SQL SELECT to load SQL SELECT to load
the first orderthe first order
This will This will execute an execute an
SQL SQL UPDATEUPDATE
![Page 34: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/34.jpg)
Deleting Existing DataDeleting Existing Data
Delete is done by Delete is done by DeleteObjectDeleteObject()() on the specified entity collectionon the specified entity collection
SaveChangesSaveChanges()() method performs the method performs the delete action in the databasedelete action 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 savenorthwindEntities.Orders.DeleteObject(order);northwindEntities.Orders.DeleteObject(order);northwindEntities.SaveChanges();northwindEntities.SaveChanges();
This will This will execute an execute an SQL DELETE SQL DELETE commandcommand
![Page 35: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/35.jpg)
CRUD Operations CRUD Operations with Entity with Entity FrameworkFramework
Live DemoLive Demo
![Page 36: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/36.jpg)
Executing Executing Native SQL Native SQL
QueriesQueriesParameterless and ParameterizedParameterless and Parameterized
![Page 37: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/37.jpg)
Executing Native SQL Executing Native SQL QueriesQueries
Executing a native SQL query in Executing a native SQL query in Entity Framework directly in its Entity Framework directly in its database store:database store:
Example:Example:
Examples are shown in SQL Server Examples are shown in SQL Server but the same can be done for any but the same can be done for any other databaseother database
ctx.ExecuteStoreQuery<return-type>(native-SQL-ctx.ExecuteStoreQuery<return-type>(native-SQL-query);query);
string query = "SELECT count(*) FROM string query = "SELECT count(*) FROM dbo.Customers";dbo.Customers";var queryResult = var queryResult = ctx.ExecuteStoreQuery<int>(query);ctx.ExecuteStoreQuery<int>(query);int customersCount = queryResult.FirstOrDefault();int customersCount = queryResult.FirstOrDefault();
37
![Page 38: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/38.jpg)
Executing Native SQL Executing Native SQL Queries (2)Queries (2)
NorthwindEntities context = new NorthwindEntities context = new NorthwindEntities();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
![Page 39: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/39.jpg)
Executing Executing Native SQL Native SQL
QueriesQueriesLive DemoLive Demo
![Page 40: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/40.jpg)
The N+1 Query The N+1 Query ProblemProblemWhat is the N+1 Query Problem and How What is the N+1 Query Problem and How
to Avoid It?to Avoid It?
![Page 41: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/41.jpg)
The N+1 Query ProblemThe N+1 Query Problem What is the What is the N+1 Query ProblemN+1 Query Problem??
Imagine a database that contains Imagine a database that contains tables tables CustomersCustomers and and OrdersOrders A customer has multiple orders (one-A customer has multiple orders (one-
to-many relationship)to-many relationship)
We want to print each We want to print each CustomerCustomer and and its its OrdersOrders::foreach (var cust in context.Customers)foreach (var cust in context.Customers){{ Console.WriteLine(cust.CompanyName + "\Console.WriteLine(cust.CompanyName + "\nOrders:");nOrders:"); foreach (var order in cust.Orders) foreach (var order in cust.Orders) {{ Console.WriteLine("{0}", order.OrderID);Console.WriteLine("{0}", order.OrderID); }}}}
41
![Page 42: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/42.jpg)
The N+1 Query Problem The N+1 Query Problem (2)(2)
foreach (var cust in context.Customers)foreach (var cust in context.Customers){{ Console.WriteLine(cust.CompanyName + "\Console.WriteLine(cust.CompanyName + "\nOrders:");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 A single query to retrieve the countriescountries
Additional N queries to Additional N queries to retrieve the cities in retrieve the cities in
each countryeach country Imagine we have 100 countries in the Imagine we have 100 countries in the databasedatabase That's 101 SQL queries That'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 This code will execute N+1 DB queries:queries:
42
![Page 43: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/43.jpg)
Solution to the N+1 Solution to the N+1 Query ProblemQuery Problem
Fortunately there is an easy way in Fortunately there is an easy way in EF to avoid the N+1 query problemEF to avoid the N+1 query problem
43
foreach (var country in foreach (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); }}}}
Using Using Include(…)Include(…) method only method only one SQL query with join is made one SQL query with join is made
to get the child entitiesto get the child entities
No additional SQL queries No additional SQL queries are made here for the are made here for the
child entitieschild entities
![Page 44: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/44.jpg)
Solution to the Solution to the N+1 Query N+1 Query
ProblemProblemLive DemoLive Demo
![Page 45: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/45.jpg)
Joining and Joining and Grouping Grouping
TablesTablesJoin and Group Using Join and Group Using LINQLINQ
![Page 46: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/46.jpg)
Joining Tables in EFJoining Tables in EF In In EFEF we can join tables in we can join tables in LINQLINQ or or
by using extension methods on by using extension methods on IEnumerable<T>IEnumerable<T> The same way like when joining The same way like when joining
collectionscollections
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.Country Country = 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.Country Country = customer.Country };};
northwindEntities.Customers. northwindEntities.Customers. Join(northwindEntities.Suppliers, Join(northwindEntities.Suppliers, (c=>c.Country), (s=>s.Country), (c=>c.Country), (s=>s.Country), (c,s)=> (c,s)=> new {Customer = c.CompanyName, new {Customer = c.CompanyName, Supplier = Supplier = s.CompanyName, Country = s.CompanyName, Country = c.Country });c.Country });
northwindEntities.Customers. northwindEntities.Customers. Join(northwindEntities.Suppliers, Join(northwindEntities.Suppliers, (c=>c.Country), (s=>s.Country), (c=>c.Country), (s=>s.Country), (c,s)=> (c,s)=> new {Customer = c.CompanyName, new {Customer = c.CompanyName, Supplier = Supplier = s.CompanyName, Country = s.CompanyName, Country = c.Country });c.Country });
46
![Page 47: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/47.jpg)
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 The same ways as with collections in LINQin 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
![Page 48: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/48.jpg)
Joining and Joining and Grouping Grouping
TablesTablesLive DemoLive Demo
![Page 49: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/49.jpg)
Attaching and Attaching and Detaching Detaching
ObjectsObjects
![Page 50: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/50.jpg)
Attaching and Attaching and Detaching ObjectsDetaching Objects
In Entity Framework, objects can be In Entity Framework, objects can be attached to or detached from an attached to or detached from an object contextobject context
AttachedAttached objects are tracked and objects are tracked and managed by the managed by the ObjectContextObjectContext SaveChanges()SaveChanges() persists all changes in DB persists all changes in DB
DetachedDetached objects are not referenced objects are not referenced by the by the ObjectContextObjectContext Behave like a normal objects, like all Behave like a normal objects, like all
others, which are not related to EFothers, which are not related to EF50
![Page 51: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/51.jpg)
Attaching Detached Attaching Detached ObjectsObjects
When a query is executed inside an When a query is executed inside an ObjectContextObjectContext, the returned objects , the returned objects are automatically attached to itare automatically attached to it
When a context is destroyed, all When a context is destroyed, all objects in it are automatically objects in it are automatically detacheddetached E.g. in Web applications between the E.g. in Web applications between the
requestsrequests You might late attach to a new You might late attach to a new
context objects that have been context objects that have been previously detachedpreviously detached
51
![Page 52: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/52.jpg)
Detaching ObjectsDetaching Objects When an object is detached?When an object is detached?
When we obtain the object from an When we obtain the object from an ObjectContextObjectContext and the and the DisposeDispose it it
Manually: by calling Manually: by calling DetachDetach(…) (…) methodmethod
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 Now the returned product is detachedis detached
![Page 53: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/53.jpg)
Attaching ObjectsAttaching Objects When we want to update a When we want to update a
detached object we need to detached object we need to reattach it and the update itreattach it and the update it Done by the Done by the Attach(…)Attach(…) method of method of
the contextthe contextvoid UpdatePrice(Product product, decimal void UpdatePrice(Product product, decimal newPrice)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
![Page 54: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/54.jpg)
Attaching and Attaching and Detaching Detaching
ObjectsObjectsLive DemoLive Demo
![Page 55: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/55.jpg)
Using Transactions in Using Transactions in EFEF
Just Use the Just Use the TransactionScopeTransactionScope Class Class
![Page 56: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/56.jpg)
Using Transactions in Using Transactions in EFEF
To perform transactional logic, just To perform transactional logic, just use the use the TransactionScopeTransactionScope class class You may need to add reference to You may need to add reference to System.Transactions.dllSystem.Transactions.dll
using (TransactionScope scope = new using (TransactionScope scope = new TransactionScope())TransactionScope()){{ NorthwindEntities context = new NorthwindEntities context = new NorthwindEntities();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
![Page 57: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/57.jpg)
Transactions in EFTransactions in EFLive DemoLive Demo
![Page 58: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/58.jpg)
Questions?
Entity FrameworkEntity Framework
![Page 59: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/59.jpg)
ExercisesExercises1.1. Using the Visual Studio Entity Framework Using the Visual Studio Entity Framework
designer create a designer create a ObjectContextObjectContext for the for the NorthwindNorthwind database database
2.2. Create a DAO class with static methods which Create a DAO class with static methods which provide functionality for inserting, modifying provide functionality for inserting, modifying and deleting customers. Write a testing class.and deleting customers. Write a testing class.
3.3. Write a method that finds all customers who Write a method that finds all customers who have orders made in 1997 and shipped to have orders made in 1997 and shipped to Canada.Canada.
4.4. Implement previous by using native SQL query Implement previous by using native SQL query and executing it through the and executing it through the ObjectContextObjectContext..
5.5. Write a method that finds all the sales by Write a method that finds all the sales by specified region and period (start / end dates).specified region and period (start / end dates).
![Page 60: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/60.jpg)
Exercises (2)Exercises (2)6.6. Create a database called Create a database called NorthwindTwinNorthwindTwin with with
the same structure as the same structure as NorthwindNorthwind using the using the features from features from ObjectContextObjectContext. Find for the API . Find for the API for schema generation in MSDN or in Google.for schema generation in MSDN or in Google.
7.7. Try to open two different data contexts and Try to open two different data contexts and perform concurrent changes on the same perform concurrent changes on the same records. What will happen at records. What will happen at SaveChanges()SaveChanges()? ? How to deal with it?How to deal with it?
8.8. By inheriting the By inheriting the EmployeeEmployee entity class create entity class create a class which allows employees to access a class which allows employees to access their corresponding territories as property of their corresponding territories as property of type type EntitySet<T>EntitySet<T>..
![Page 61: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/61.jpg)
Exercises (3)Exercises (3)
9.9. Create a method that places a new order Create a method that places a new order in the in the NorthwindNorthwind database. The order database. The order should contain several order items. Use should contain several order items. Use transaction to ensure the data transaction to ensure the data consistency.consistency.
10.10.Create a stored procedures in the Create a stored procedures in the NorthwindNorthwind database for finding the total database for finding the total incomes for given supplier name and incomes for given supplier name and period (start date, end date). Implement period (start date, end date). Implement a C# method that calls the stored a C# method that calls the stored procedure and returns the retuned procedure and returns the retuned record set.record set. 61
![Page 62: ADO.NET Entity Framework](https://reader037.vdocuments.site/reader037/viewer/2022102716/554ebbbbb4c905064d8b45c1/html5/thumbnails/62.jpg)
Exercises (4)Exercises (4)
11.11. Create a database holding users and Create a database holding users and groups. Create a transactional EF groups. Create a transactional EF based method that creates an user and based method that creates an user and puts it in a group "Admins". In case the puts it in a group "Admins". In case the group "Admins" do not exist, create the group "Admins" do not exist, create the group in the same transaction. If some group in the same transaction. If some of the operations fail (e.g. the of the operations fail (e.g. the username already exist), cancel the username already exist), cancel the entire transaction.entire transaction.
62