orm concepts, ado.net entity framework (ef), objectcontext doncho minkov telerik corporation

of 55 /55
ADO.NET Entity Framework ORM Concepts, ADO.NET Entity Framework (EF), ObjectContext Doncho Minkov www.telerik. com Telerik Corporation

Author: shon-norris

Post on 02-Jan-2016




4 download

Embed Size (px)



ADO.NET Entity FrameworkORM Concepts, ADO.NET EntityFramework (EF), ObjectContext

Doncho Minkovwww.telerik.comTelerik Corporation

Table of ContentsORM Technologies Basic ConceptsEntity FrameworkOverviewPrinting the native SQL queriesLINQ ComponentsEntity FilesThe Visual Studio DesignerObjectContext Class and CRUD Operations2

Table of Contents (2)Executing Native SQL QueriesParamerterless QueriesParameterized QueriesThe N+1 Query ProblemJoining and Grouping EntitiesAttaching and Detaching Objects3

Introduction to ORMObject-Relational Mapping (ORM) Technologies

ORM TechnologiesObject-Relational Mapping (ORM) is a programming technique for automatic mapping and converting dataBetween relational database tables and object-oriented classes and objectsORM creates a virtual object database Which can be used from within the programming language, e.g. C# or JavaORM frameworks automate the ORM processA.k.a. object-relational persistence frameworks5ORM FrameworksORM frameworks typically provide the following functionality:Creating object model by database schemaCreating database schema by object modelQuerying data by object-oriented APIData manipulation operationsCRUD create, retrieve, update, deleteORM frameworks automatically generate SQL to perform the requested data operations6ORM Mapping ExampleDatabase and Entities mapping diagrams for a subset of the Northwind database7

Relational database schema

ORM Entities (C# Classes)ORMFramework

ORM AdvantagesObject-relational mapping advantagesDeveloper productivityWriting less codeAbstract from differences between object and relational worldComplexity hidden within ORMManageability of the CRUD operations for complex relationshipsEasier maintainability8Approaches to ORMTemplate-based code generation vs. entity classes mappingsSQL generation (design time / runtime) vs. mapping existing SQLEntity classes representationEntities are just POCO (Plain Old C# Objects)Entities implement special IPersistent interface or extend PersistentBase classConfiguring mappingsDB schema data vs. XML vs. annotations9*07/16/969##Object Persistence FrameworksCode generation toolsGenerate C#, XML and other filesSource code is compiled and used as APICan be highly customizedObject-relational mapping toolsMappings are described in XML files or built in the classes as attributesNo source code generationUse of single standard API

10ORM Frameworks in .NETBuilt-in ORM tools in .NET Framework and VSADO.NET Entity FrameworkLINQ-to-SQLBoth combine entity class mappings and code generation, SQL is generated at runtimeThird party ORM toolsNHibernate the old daddy of ORMTelerik OpenAccess ORM11ADO.NET Entity FrameworkObject Relation Persistence Framework

Overview of ADO.NET EFEntity Framework (EF) is a standard ORM framework, part of .NETProvides a run-time infrastructure for managing SQL-based database data as .NET objectsThe relational database schema is mapped to an object model (classes and associations)Visual Studio has built-in tools for generating Entity Framework SQL data mappingsData mappings consist of C# classes and XMLA standard data manipulation API is provided13Overview of ADO.NET EF (2)Entity Framework provides an application programming interface (API)For accessing data stored in database serversBuilt on the top of ADO.NET and LINQLINQ to Entities is Microsofts entry-level LINQ-enabled ORM implementation for database serversWorks with SQL Server and SQL Server ExpressCould work with MySQL, SQLite, Oracle, etc.Maps tables and one-to-many and many-to-many relationships14Entity Data ModelThe Entity Data Model (EDM) is a schema language for entities, consisting of:Conceptual model (CSDL)Mapping (MSL)Storage Model (SSDL)15

Entity Framework Architecture16

Entity Framework FeaturesEntity Framework (EF) standard features:Maps tables, views, stored procedures and functions as .NET objectsProvides LINQ-based data queriesExecuted as SQL SELECTs on the database serverCRUD operations Create/Read/Update/DeleteCreate compiled queries for executing the same parameterized query multiple timesCreating or deleting the database schema17Entity Framework LifecycleWhen the application startsEF translates into SQL the language-integrated queries in the object modelSends them to the database for later execution18

Entity Framework Lifecycle (2)When the database returns the resultsEntity Framework translates the database rows back to .NET objectsThe database server is transparent, hidden behind the APILINQ is executed over IQueryableAt compile time a query expression tree is emittedAt runtime SQL is generated and executed19EF ComponentsThe ObjectContext classObjectContext holds the database connection and the entity classesProvides LINQ-based data accessImplements identity tracking, change tracking, and API for CRUD operationsEntity classesEach database table is typically mapped to a single entity class (C# class)20EF Components (2)AssociationsAn association is a primary key / foreign key based relationship between two entity classesAllows navigation from one entity to another, e.g. Student.CoursesConcurrency controlEntity Framework uses optimistic concurrency control (no locking by default)Provides automatic concurrency conflict detection and means for conflicts resolution21LINQ to Entity Files (.edmx)Visual Studio has built-in Entity Framework data designer and code generatorMappings are stored in .edmx files (Entity Data Model XML).edmx is an XML fileHolds metadata representing the database schema (CSDL, MSL and SSDL models).Designer.cs file contains the C# entity classes and the ObjectContext classOne entity class for each mapped database table22LINQ to Entity Files ExampleEDMX mapping for the Categories table from Northwind database in SQL Server23

Entity class CategoryThe Entity Framework Designer in Visual StudioLive Demo

The ObjectContext ClassThe ObjectContext class is generated by the Visual Studio designerObjectContext provides:Methods for accessing entities (object sets) and creating new entities (AddTo methods)Ability to manipulate database data though entity classes (read, modify, delete, insert)Easily navigate through the table relationshipsExecuting LINQ queries as native SQL queriesCreate the DB schema in the database server25Using ObjectContext ClassFirst create instance of the ObjectContext:

In the constructor you can pass a database connection string and mapping sourceObjectContext propertiesConnection the SqlConnection to be usedCommandTimeout timeout for database SQL commands executionAll entity classes (tables) are listed as propertiese.g. ObjectSet Orders { get; }26NorthwindEntities northwind = new NorthwindEntities();26Reading Data with LINQ QueryExecuting LINQ-to-Entities query over EF entity:

Customers property in the ObjectContext:27public partial class NorthwindEntities : ObjectContext{ public ObjectSet Customers { get { } }}NorthwindEntities context = new NorthwindEntities();var customers = from c in context.Customers where c.City == "London" select c;The query will be executes as SQL command in the databaseLogging the Native SQL QueriesTo print the native database SQL commands executed on the server use the following:28var query = context.Countries;Console.WriteLine((query as ObjectQuery).ToTraceString());This will print the SQL native query executed at the database server to select the CountriesCan be printed to file using StreamWriter class instead of Console class28Retrieving Data with LINQ to EntitiesLive Demo

Creating New DataTo create a new database row use the method AddObject() of the corresponding collection:30// Create new order objectOrder order = new Order(){ OrderDate = DateTime.Now, ShipName = "Titanic", ShippedDate = new DateTime(1912, 4, 15), ShipCity = "Bottom Of The Ocean"};// Mark the object for insertingcontext.Orders.AddObject(order);context.SaveChanges();This will execute an SQL INSERTSaveChanges() method call is required to post the SQL commands to the databaseCreating New Data (2)Creating new row can also be done by using the AddTo + The_Entity_Name method directly on the ObjectContextThis method is depricatedBetter use the other one31// Mark the object for insertingcontext.AddToOrders(order);

// Post changes to database (execute SQL INSERTs)context.SaveChanges();Cascading InsertsWe can also add cascading entities to the database:32Country spain = new Country();spain.Name = "Spain";spain.Population = "46 030 10";spain.Cities.Add( new City { Name = "Barcelona"} );spain.Cities.Add( new City { Name = "Madrid"} );countryEntities.Countries.AddObject(spain);countryEntities.SaveChanges();This way we don't have to add each City individuallyThey will be added when the Country entity (Spain) is inserted to the databaseUpdating Existing DataObjectContext allows modifying entity properties and persisting them in the databaseJust load an entity, modify it and call SaveChanges()The ObjectContext automatically tracks all changes made on its entity objects33Order order = northwindEntities.Orders.First();order.OrderDate = DateTime.Now;context.SaveChanges();This will execute an SQL SELECT to load the first orderThis will execute an SQL UPDATEDeleting Existing DataDelete is done by DeleteObject() on the specified entity collectionSaveChanges() method performs the delete action in the database34Order order = northwindEntities.Orders.First();// Mark the entity for deleting on the next savenorthwindEntities.Orders.DeleteObject(order);northwindEntities.SaveChanges();This will execute an SQL DELETE commandCRUD Operations with Entity FrameworkLive Demo

Executing Native SQL QueriesParameterless and Parameterized

Executing Native SQL QueriesExecuting a native SQL query in Entity Framework directly in its database store:


Examples are shown in SQL Server but the same can be done for any other databasectx.ExecuteStoreQuery(native-SQL-query);string query = "SELECT count(*) FROM dbo.Customers";var queryResult = ctx.ExecuteStoreQuery(query);int customersCount = queryResult.FirstOrDefault();37Executing Native SQL Queries (2)NorthwindEntities context = new NorthwindEntities();string nativeSQLQuery = "SELECT FirstName + ' ' + LastName " + "FROM dbo.Employees " + "WHERE Country = {0} AND City = {1}";object[] parameters = { country, city };var employees = context.ExecuteStoreQuery( nativeSQLQuery, parameters);foreach (var emp in employees){ Console.WriteLine(emp);}Native SQL queries can also be parameterized:38Executing Native SQL QueriesLive Demo

The N+1 Query ProblemWhat is the N+1 Query Problem and How to Avoid It?

The N+1 Query ProblemWhat is the N+1 Query Problem?Imagine a database that contains tables Customers and OrdersA customer has multiple orders (one-to-many relationship)We want to print each Customer and its Orders:foreach (var cust in context.Customers){ Console.WriteLine(cust.CompanyName + "\nOrders:"); foreach (var order in cust.Orders) { Console.WriteLine("{0}", order.OrderID); }}41The N+1 Query Problem (2)foreach (var cust in context.Customers){ Console.WriteLine(cust.CompanyName + "\nOrders:"); foreach (var order in cust.Orders) { Console.WriteLine("{0}", order.OrderID); }}A single query to retrieve the countriesAdditional N queries to retrieve the cities in each countryImagine we have 100 countries in the databaseThat's 101 SQL queries very slow!We could do the same with a single SQL queryThis code will execute N+1 DB queries:42Solution to the N+1 Query ProblemFortunately there is an easy way in EF to avoid the N+1 query problem43foreach (var country in countriesEntities.Countries.Include("Cities")){ foreach (var city in country.Cities) { Console.WriteLine(" {0}", city.CityName); }}Using Include() method only one SQL query with join is made to get the child entitiesNo additional SQL queries are made here for the child entitiesSolution to the N+1 Query ProblemLive Demo

Joining and Grouping TablesJoin and Group Using LINQ

Joining Tables in EFIn EF we can join tables in LINQ or by using extension methods on IEnumerableThe same way like when joining collectionsvar custSuppl = from customer in northwindEntities.Customers join supplier in northwindEntities.Suppliers on customer.Country equals supplier.Country select new { CustomerName = customer.CompanyName, Supplier = supplier.CompanyName, Country = customer.Country };northwindEntities.Customers. Join(northwindEntities.Suppliers, (c=>c.Country), (s=>s.Country), (c,s)=> new {Customer = c.CompanyName, Supplier = s.CompanyName, Country = c.Country });46Grouping Tables in EFGrouping also can be done by LINQThe same ways as with collections in LINQGrouping with LINQ:

Grouping with extension methods:

var groupedCustomers = from customer in northwindEntities.Customers group customer by Customer.Country;var groupedCustomers = northwindEntities.Customers.GroupBy( customer => customer.Country);47Joining and Grouping TablesLive Demo

Attaching and Detaching Objects

Attaching and Detaching ObjectsIn Entity Framework, objects can be attached to or detached from an object contextAttached objects are tracked and managed by the ObjectContextSaveChanges() persists all changes in DBDetached objects are not referenced by the ObjectContextBehave like a normal objects, like all others, which are not related to EF

50Attaching Detached ObjectsWhen a query is executed inside an ObjectContext, the returned objects are automatically attached to itWhen a context is destroyed, all objects in it are automatically detachedE.g. in Web applications between the requestsYou might late attach to a new context objects that have been previously detached51Detaching ObjectsWhen an object is detached?When we obtain the object from an ObjectContext and the Dispose itManually: by calling Detach() methodProduct GetProduct(int id){ using (NorthwindEntities northwindEntities = new NorthwindEntities()) { return northwindEntities.Products.First( p => p.ProductID == id); }}52Now the returned product is detachedAttaching ObjectsWhen we want to update a detached object we need to reattach it and the update itDone by the Attach() method of the contextvoid UpdatePrice(Product product, decimal newPrice){ using (NorthwindEntities northwindEntities = new NorthwindEntities()) { northwindEntities.Products.Attach(product); product.UnitPrice = newPrice; northwindEntities.SaveChanges(); }}53Attaching and Detaching ObjectsLive Demo


????Entity Framework???