SlideShare una empresa de Scribd logo
1 de 55
Entity Framework
@ 5,000 Feet
 Rob Vettor , C# MVP
 robvettor@hotmail.com




Rob Vettor               1
This is Your Life...

      You build applications for a living
      Each talks to relational database
      Learn (at least) 2 different languages (C# and SQL)
             – Different syntax
             – Different type systems
             – Different tools
             – Different paradigms: Object vs. Procedural

      Also must learn the API that binds together: ADO.NET
             – Powerful, but fragile and time-consuming



Rob Vettor                                                      2
Here is What You Do…

 using (SQLConnection conn = new SQLConnection(“<conn string>”);
 {
    conn.Open();
    SQLCommand cmd = conn.CreateCommand();
    cmd.CommandText = “sp_StoredProc”;
    cmd.parameters.AddWithValue(“@City”, “Dallas”);
    using (SQLDataReader rdr = cmd.ExecuteReader())
    {
      while (rdr.read())
      {
         string name = rdr.GetString(0);            Parameters loosely bound: --
         string city = rdr.GetString(1);             Strings! No compile
                                                    Names, types, number of
                                                      Results are loosely typed
      }                                             not checked or Intellisense
                                                     time check until runtime
    }
 }

 Powerful, but fragile and time-consuming



Rob Vettor                                                                 3
Bigger Problem

            Objects != Relational Data
 OO been around for decades; relational databases even
  longer
 Bridging the gap between has been time consuming and
  expensive:
  – Legacy ADO.NET                                        Objects
                                    Relational Data
  – Hand-built DALs
  – 3rd party frameworks

 But, the core problem remains!


                                                      4
So, Now…

     Instead of building business functionality,
        Application                                           Database


       Customer.cs                                           dbo.customer
                                 Mapping Code
                              Transform OO to DB
         Order.cs                                             dbo.order




                        We build plumbing
                          to move data back and forth
                      from data store to business objects.

Rob Vettor                                                                  5
Goals

     Fly over the Entity Framework @ 5,000 feet
     What it is
     What it does
     How it works
     Why it exists
     Test drive examples
     Where to find more


Rob Vettor                                    6
Autobiographical Stuff…
   Architect/Team Lead
   C# MVP
   INETA Regional Speaker
   Frequent Presenter
   User Group Leader
   Developer Guidance Council member




Rob Ve                                            7
Spot Survey

     How many use EF in production app?
     How many have looked at EF?
     How many have looked at LINQ?
     How many use Visual Studio 2008?
     How many use Visual Studio 2008 and
        not LINQ?




Rob Vettor                                  8
Appeal

     Need your feedback and support:
         – If you like presentation, please send email
         – Consider lobbying User Group leader to have
           me present any of the following:
             – Getting Started with Entity Framework
             – Getting Started with LINQ
             – Advanced LINQ
             – Entity Framework 4.0
             – ADO.NET Data Services




Rob Vettor                                                  9
Agenda
s Define Entity Framework
s Explore its Architecture
s Map Conceptual Model
s Program Conceptual Model
s Examine Key Concepts
s Compare EF vs. L2S
s How to get started
             –


Rob Vettor                        10
What is the Entity Framework?
     Released in July 2008, EF is a data access framework
    from Microsoft that helps bridge the gap between data
    structures and objects in your applications.


                 ADO.NET Evolution
“Legacy”
ADO.NET                           ADO.NET       Azure
                                                            RIA
   2.0                              Data        Table
                                                          Services
                                  Services     Services



                   Underlying Framework for…


Rob Vettor                                                 11
What Does It Do?

s Develop against conceptual view of your data,
  instead of data store itself
  s Automatically generates strongly-typed entity objects that
    can be customized beyond 1-1 mapping
  s Automatically generates mapping/plumbing code
  s Automatically translates LINQ queries to database queries
  s Automatically materializes objects from data store calls
  s Automatically tracks changes, generating updates/inserts
  s Delivers variety of visual modeling tools




 Rob Vettor                                           12
From a LINQ Perspective

   Query Operators              C# 3.0               VB 9.0



                          LINQ Proviers

    LINQ to    LINQ to       LINQ to      LINQ to      LINQ to
    Objects    Datasets        SQL        Entities      XML


                                                         <book>
                                                           <title/>
                                                         <author/>
                                                          <year/>
                                                          <price/>
                                                         </book>




     Objects                                             XML
                            Relational
Rob Vettor                                                    13
ADO.NET Perspective

              Entity Framework
                                          V3.0
                       LINQ to Entities, Entity SQL
                                                            Programming
                  ADO.NET Entity Provider (entity client)
                                                               Model
                         Conceptual Data Model
        Mapping




                      Legacy ADO.NET 2.0 does not go away!

                    ADO.NET Data Provider
                    (SqlClient, OracleClient)
                     Reader            Connection                Store
                    Adapter            Command

Rob Vettor                                                               14
Architectural Layering


                      Object
                      Services



                      Entity
                      Client



                                 Core
                      EDM        of EF




                                 15

Rob Vettor
Entity Data Model
s Set of objects that describe structure of your business
  data and map to your underlying data store
     Contained in Three XML sections stored in *.edmx file:


          Database                                             Entity
          Schema                                              Objects


        Storage Model             Mapping                 Conceptual Model


Database                                             UI        OO       Services

s Abstracts developer from a model pleasing to a DBA
  (normalized, maintainable, efficient, secure), but
  complicated to program against
  Rob Vettor                                                             16
Summary

s Entity Framework is data access framework that
  bridges gap between data and objects
s Sits beneath many of Microsoft’s new offerings:
  ADODS, Azure Tables, RIA Services
s Automatically creates entity objects and mappings
s Transforms LINQ Queries into SQL
s Delivers flexible object model that enables you to
  map data to objects as you like



Rob Vettor                                       17
Agenda

s The Problem
s The EF and EDM

sMapping a Conceptual Model…
s Programming a Conceptual Model
s Key Concepts…
s EF vs. L2S
s Advanced Mapping
s How to get started


Rob Vettor                              18
Map Conceptual Model
s Designer Tour…
      With mapping wizard, create a new Entity Data Model
      Examine entities, scalar and navigation properties in EDM
         Designer,
        Look at the Model Browser
        Look at the Mapping Details
        Look at the EDMX file
        Most importantly, look at generated entity classes
s End up with object-representation of our data store
s DEMO


Rob Vettor                                                     19
Mapping Recap




                                                            Many-to-Many
             Relationship                              Represented by navigation
                        Scalar Property
                                   Navigation Property
    Object that describes an that is to related entity. Properties. Suppresses
                         Value Pointer
    Association, denoted by in Enable app to navigate      association entity
                     contained the entity
   the multiplicity of endpoint        to and from.
          Entity
  Key domain object
   distinguished by
       its identity

Rob Vettor                                                           20
Agenda

s The Problem
s The EF and EDM
s Mapping a Conceptual Model

sProgramming a Conceptual Model…
s Key Concepts
s EF vs. L2S
s Advanced Mapping
s How to get started


Rob Vettor                          21
Programing Conceptual Model
                Two APIs available for coding against EDM

                      Entity                   Object
                      Client                   Services



     s New ADO.NET data provider
       Query against conceptual model with LINQ
         Managed new code generates eSQL
     s Implements LINQ SQL dialect  SQL
        Returns ‘hierarchical’ result set , not tabular Intellisense
         Compile time type checking, debugging and
        Closely resembles ADO.NET, requires connections,
     s Query results are “materialized” into strongly-typed objects
             commands, returns data readers
     s Provides automatic change tracking
        Delivers high performance – returns data not objects
     s Manages concurrency and transactions
        Favor when need plain data, not “materialized” entities


Rob Vettor                                                         22
Two Simple Demos
s eSQL Demo… and LINQ-To-Entities Demo…
      Query customers from our conceptual model
      Return all customers in Oregon
      Render in GridView


s View generated SQL in SQL Profiler
s Demonstrate “Query Syntax” vs. “Method Syntax”
s Remember: We are querying conceptual model, not
  data store



Rob Vettor                                         23
Agenda
s The Problem
s The EF and EDM
s Mapping a Conceptual Model
s Programming a Conceptual Model

sKey Concepts…
s EF vs. L2S
s Advanced Mapping
s How to get started


Rob Vettor                              24
Key Concept: Object Context
     using (NorthwindEFEntities ctx = new NorthwindEFEntities())

– Workhouse of EF
  – Entry point to Entity Framework
                                                            Object
  – Manages connection to data store                        Context

  – Generates SQL queries against store
  – Marshals data across boundaries and                     Entity
                                                           Designer
    materializes entity objects
  – Acts as local cache for storing the
    materialized objects                                 Target Entity

  – Maintains full change tracking and                 Uses factory to
    concurrency management                             Instantiate entity



 Rob Vettor                                                        25
Associations/Navigation Properties

s When generating from database, EF infers <PK><FK>
  relationships and generates navigation properties
    Multiplicity
    Direction

  avigate conceptual model without
  explicit joins

  avigation properties, enable us to
  ‘dot’ into related objects




 Rob Vettor                                      26
Navigation Properties
    – From Order, use navigation property to find related OrderDetail entities
                        from o in Order
                        where o.OrderDetails.unitPrice > 20
                        select o;
  Order
  OrderrID <pk>
                       Order maps reference to collection of Order Details objects (EntitySet Type)



        From OrderDetails, use navigation property to find Order entities

                        from d in OrderDetails
                        where d.Order.orderID == 1
  OrderDetail           select d;
  OriderDetailID<pk>
  OrderD <fk>          Order Details maps reference to single Order object (EntityRef Type)



s DEMO

     Rob Vettor                                                                            27
Projection
s Shaping or molding the data returned by LINQ query to
  include only what you need.
   Can project entire sequence from collection…
   Can project single value…
   Can project selected fields…
     – Using Concrete Type
     – Using Anonymous Type…
       – Builds type on-the-fly
       – select new { … } (no type name followed by curly braces)
       – Implements Type Inference…
         – var keyword tells compiler to infer strong type from right-side expression

sDEMO
                                                                           28
Parameterized Queries vs. Sprocs
      s LINQ fully supports both approaches
      s Parameterized queries
             s Good for CRUD operations
             s Executions plans are cached and reused
             s Automatically generated by LINQ framework
             s Do require server permissions at the table level
      s Stored Procedures
             s More complex business logic (beyond CRUD)
             s Security, performance, auditing



Rob Vettor                                                 29
Deferred Loading
  s LINQ is built on concept of “deferred execution”
     Most query operators don’t execute when declared
          – //-- First, define query
          –              var query = from c in ctx.Customers
  s                       where c.Region == "OR"
  s                       orderby c.CompanyName
Define query
  s
 and store                select c;                         Execute query when
 in variable
  s                 //-- Then, execute query                  absolutely necessary
  s                 gvQuery.DataSource = query;
  s                 gvQuery.DataBind();
        Query gets executed when enumerated
               – Bound to a DataBound control
               – Execute within ForEach loop Iteration
               – Transformed to collection ToList(), ToArray(), etc

  Rob Vettor                                                           30
Eager Loading
s Force LINQ to immediately execute query
   Operators that return a singleton:
             – Aggregate Methods
             – Element Methods
             –    Retrieve specific element from sequence
             –    First(), Last(), ElementAt()
      Collection-Conversion Operators
             – ToArray(), ToList(), ToDictionary(), ToLookup()

s Include() method supports eager execution:
      Retrieves parent and child entities immediately, not when
     referenced
s (No Demo Yet)



Rob Vettor                                                              31
Loading Single Objects
s Basic Example
             – Run SQL Profiler and step thru code
             – Demonstrate Deferred and Eager loading
             – Explore when execution takes place
             – See how each enumeration of same query
               generates a separate call to DB


s DEMO NOW!



Rob Vettor                                              32
Loading Object Graphs
s Object Graph: Set of individual, but related objects, that
  together form a logical whole unit

    Customer     Order   Order Detail   Product   Category


s By default, with deferred execution, child objects load one
  at a time (separate data store call for each) as needed.
s We can use Include() method to predefine the object graph,
  forcing all entire graph to load at once with single query
s DEMO
      Load object graph including Orders, Order Details
         and Products
Rob Vettor                                             33
Deferred vs. Immediate
    Deferred Execution
        – Benefits:
             – Fetches data only when needed, not all at once
             – Minimize network traffic, memory consumption and
               load on database
             – Great for when can but fetch objects as user
               requests them
        – Drawbacks:
             – Chatty Interface: Each request for child record
               invokes explicit database query



Rob Vettor                                                  34
Deferred vs. Immediate
    Immediate Execution
      – Benefits:
             – Singe query returns all data
             – Great if you know that you will need all data returned
        – Drawbacks:
             – Large amount of data returned, whether used or not.




Rob Vettor                                                  35
Updates/Change Tracking
s ObjectContext automatically tracks changes to entities via
  the ObjectStateManager object
    Upon retrieval, caches original values
    Tracks any changes made to entities
    Dynamically constructs update/insert SQL statements
             – If not updating an entity, disable Change Tracking
               – ctx.Products.MergeOption = MergeOption.NoTracking;
s Next DEMO
   Demonstrate change tracking
   Update postal code and freight charge for an order
   Watch ObjectStateManager track both changes and original values
   See it generate parameterized SQL update statement
   Explicitly wrap in transaction

Rob Vettor                                                            36
Inserts
 s Inserting with EF is multi-step process
        s Create new (disconnected) entity object and populate
        s Attach new entity to the ObjectContext
        s Call SaveChanges() to commit to database
 s Next DEMO
        s Show how ObjectContext leverages inferred
          relationship
           s Inserts both parent and child records in correct order
           s Maintains foreign key relationship
           s Automatically manages the identity values
        s Show that ObjectContext automatically returns new identity key
          and assigns to new entity objects




Rob Vettor                                                       37
Agenda
s The Problem
s The EF and EDM
s Mapping a Conceptual Model
s Programming a Conceptual Model
s Key Concepts

sEF vs. L2S…
s Advanced Mapping
s How to get started


Rob Vettor                              38
History
s On the surface, appear to look and behave closely
   LTS
     – Evolved from LINQ Project, a language-development team
   EF
     – Evolved from Data Programmability Team (DPT) which
       initially focused on the Entity SQL language
     – Later adapted LINQ to work with entity objects
s LTS later moved to the Data Team
s 11/08, Data Team announced invest in EF, while
  maintaining and tweaking L2S
s Microsoft will provide migration path to EF
  and recommend EF over LTS


                                                            39
How They Differ
s General consensus:
   LTS
     – Strongly typed LINQ access for RAD against SQL Server only
     – Support s only direct Table-Per-Type (1-to-1) mapping
     – Limited out-of-the box support for complex scenarios
   EF
     – Designed for larger enterprise applications
     – Enables complex mapping complex scenarios
     – Tools and designer more robust
     – Supports inheritance and many-to-many relationships
     – Supports provider independence


                                                               40
EF vs. LTS
        Category             LINQ to SQL            Entity Framework
          Model               domain model         conceptual data model

  Databases Supported        SQL server only               Many

Complexity/Learning Curve     simple to use           complex to use

                                                slower development but more
   Development Time         rapid development
                                                         capabilities

         Mapping              Direct 1-to-1          Custom mapping

        Inheritance           hard to apply           simple to apply



          Support                  ?             $$$, resources, innovation




  Rob Vettor                                                            41
Agenda
s The Problem
s The EF and EDM
s Mapping a Conceptual Model
s Programming a Conceptual Model
s Some Intermediate Topics
s EF vs. L2S

sAdvanced Mapping…
s How to get started


Rob Vettor                              42
Advanced EDM Mapping
s EDM provides flexibility customizing conceptual model
s Most customizations occur in the conceptual model and
  depend on the mapping layer to map to underlying store
s Designer supports following customization:
   Table Per Hierarchy Inheritance mapping
   Table Per Type Inheritance mapping
   Entity (vertical) splitting




Rob Vettor                                         43
Mapping Between Layers

  Logical Schema       Table Per Type Inheritance        Conceptual Schema


             Contact
                                                           SalesPeople

     Employee


  SalesPerson
                                                             SalesOrder


     SalesOrder                                              StoreOrder

                       Table Per Hierarchy Inheritance


     Storage Schema              Mapping                      Con. Schema
         .ssdl File              .msl File                      .csdl File



Rob Vettor                                                          44
Table-Per-Hierarchy Mapping (TPH)
s Simple inheritance that maps multiple entities to single
  database table
s Mapping conditionally based on discriminator column to
  differentiate records as different types
s Quick to implement, but lacks scalability – derived from single
  database table                                      Base Type

                                                     Entities
                          Discriminator
                             Column
         Database Table

       Employee                                          Employee

       managementFlag                              ManagementEmployee


s No Demo Yet
                                          Derived Type

 Rob Vettor                                                         45
Using TPH
s Discriminator column identifies whether row belongs to
  base or derived type
s Can include additional columns for derived type whose
  value is NULL for base type (denormalized!)
s Can query on derived types without a where clause by
  using OfType() method
   from c in ctx.Customers.OfType<ManagementEmployees>()
s Show in Designer
s Demo
s Limitations
      Difficult to update discriminator column value via EF – must
         use database construct (trigger/stored proc)
Rob Vettor                                                  46
Table-Per-Type Mapping
s Inheritance spanning related database tables.
s Exposes attributes from both parent table and child table into
  single derived entity
s Defined in database with separate tables where one table
  (child) describes new type based on another table (parent)


         Database Table                      Entities

                                              Customers
              Tax Audit


         State Tax Audit                    CustomersUSA


s No Demo Yet
 Rob Vettor                                               47
Using TPT
s Eliminates need to programmatically traverse navigation
  properties to move from child (CustUSA) to parent (Cust)
  to include parent information
s When projecting on derived type, use OfType() method
   from c in ctx.Customers.OfType<CustomersUSA>()
s Show in Designer, Demo
s Limitations:
      Derived type is completely bound to parent type – cannot
       directly access derived type; only thru parent
      Cannot delete child without deleting parent
      Cannot change existing customer to CustomerUSA

Rob Vettor                                                48
Entity (Vertical) Splitting
s Map single entity to multiple tables
s Tables must share common key
s Typically for 1-to-1 relationships where one table
  provide additional information about another
        Database Tables

             Employee
                                            Entities

        EmployeeFinancial                  Employee

        EmployeePersonal


s No Demo Yet

Rob Vettor                                             49
Using Entity (Vertical) Splitting
s Vertical Entity Partitioning
   s Addresses data modeling practice of decomposing large
     table into number of smaller tables
   s Relives you from having to traverse navigation properties
     among the tables to retrieve data
   s In mapping details window, we map single entity to three
     underlying tables
          s Conceptual model contains single product entity
          s Store (SSDL) contains three product tables
          s MSL metadata maps single entity to multiple tables
          Show Mapping Details in Designer; Demo



 Rob Vettor                                                      50
Advanced EDM Mapping
s EDM enables you to decouple and customize your
  conceptual layer and design it to align more with your
  business processes, rather than the highly-normalized
  design a DBA might create
s The Mapping Detail Tool enables you to map your
  customizations to your underlying data store layer
s Designer supports most, but not all, customization
   Table Per Hierarchy Inheritance mapping
   Table Per Type Inheritance mapping
   Entity (vertical) splitting



Rob Vettor                                             51
Agenda
s The Problem
s The EF and EDM
s Mapping a Conceptual Model
s Programming a Conceptual Model
s Key Concepts
s EF vs. L2S
s Advanced Mapping

sGetting Started…

Rob Vettor                              52
EF Books




Rob Vettor          53
EF Webcasts


s Mike Taulty
     150 Screen Casts




Rob Vettor                         54
Questions?
                         Comments?
                        Suggestions?




                    robvettor@hotmail.com

             http://weblogs.asp.net/dotnetarchitect

Rob Vettor                                            55

Más contenido relacionado

La actualidad más candente

Professional Frontend Engineering
Professional Frontend EngineeringProfessional Frontend Engineering
Professional Frontend EngineeringNate Koechley
 
SeaJUG May 2012 mybatis
SeaJUG May 2012 mybatisSeaJUG May 2012 mybatis
SeaJUG May 2012 mybatisWill Iverson
 
Sql azure database under the hood
Sql azure database under the hoodSql azure database under the hood
Sql azure database under the hoodguest2dd056
 
Transforming a 15 year old model-driven application from C++ to Java
Transforming a 15 year old model-driven application from C++ to JavaTransforming a 15 year old model-driven application from C++ to Java
Transforming a 15 year old model-driven application from C++ to JavaEric Malotaux
 
LSC - Synchronizing identities @ Loadays 2010
 LSC - Synchronizing identities @ Loadays 2010 LSC - Synchronizing identities @ Loadays 2010
LSC - Synchronizing identities @ Loadays 2010RUDDER
 
Introduction To J Boss Seam
Introduction To J Boss SeamIntroduction To J Boss Seam
Introduction To J Boss Seamashishkulkarni
 
Oracle - Programatica2010
Oracle - Programatica2010Oracle - Programatica2010
Oracle - Programatica2010Agora Group
 

La actualidad más candente (8)

Professional Frontend Engineering
Professional Frontend EngineeringProfessional Frontend Engineering
Professional Frontend Engineering
 
SeaJUG May 2012 mybatis
SeaJUG May 2012 mybatisSeaJUG May 2012 mybatis
SeaJUG May 2012 mybatis
 
internet
internetinternet
internet
 
Sql azure database under the hood
Sql azure database under the hoodSql azure database under the hood
Sql azure database under the hood
 
Transforming a 15 year old model-driven application from C++ to Java
Transforming a 15 year old model-driven application from C++ to JavaTransforming a 15 year old model-driven application from C++ to Java
Transforming a 15 year old model-driven application from C++ to Java
 
LSC - Synchronizing identities @ Loadays 2010
 LSC - Synchronizing identities @ Loadays 2010 LSC - Synchronizing identities @ Loadays 2010
LSC - Synchronizing identities @ Loadays 2010
 
Introduction To J Boss Seam
Introduction To J Boss SeamIntroduction To J Boss Seam
Introduction To J Boss Seam
 
Oracle - Programatica2010
Oracle - Programatica2010Oracle - Programatica2010
Oracle - Programatica2010
 

Destacado (20)

Building data centric applications for web, desktop and mobile with Entity Fr...
Building data centric applications for web, desktop and mobile with Entity Fr...Building data centric applications for web, desktop and mobile with Entity Fr...
Building data centric applications for web, desktop and mobile with Entity Fr...
 
Code in the Cloud - Ghent - 20 February 2015
Code in the Cloud - Ghent - 20 February 2015Code in the Cloud - Ghent - 20 February 2015
Code in the Cloud - Ghent - 20 February 2015
 
Using sql server in c sharp
Using sql server in c sharpUsing sql server in c sharp
Using sql server in c sharp
 
JoomlaDay Oran, présentation du template T3 Framework
JoomlaDay Oran, présentation du template T3 FrameworkJoomlaDay Oran, présentation du template T3 Framework
JoomlaDay Oran, présentation du template T3 Framework
 
Examen 2011 exo 4
Examen 2011 exo 4Examen 2011 exo 4
Examen 2011 exo 4
 
Correction examen-java-avancé-1
Correction examen-java-avancé-1Correction examen-java-avancé-1
Correction examen-java-avancé-1
 
Correction de td poo n3
Correction de td poo n3Correction de td poo n3
Correction de td poo n3
 
Ado.net
Ado.netAdo.net
Ado.net
 
Exercice sur les classes en Java
Exercice sur les classes en JavaExercice sur les classes en Java
Exercice sur les classes en Java
 
C#2008 Black Book
C#2008 Black BookC#2008 Black Book
C#2008 Black Book
 
Atelier template
Atelier templateAtelier template
Atelier template
 
Créer un template pour Joomla 2.5
Créer un template pour Joomla 2.5Créer un template pour Joomla 2.5
Créer un template pour Joomla 2.5
 
Serie de TD 3 POO
Serie de TD 3 POOSerie de TD 3 POO
Serie de TD 3 POO
 
Apprenez à créer votre site Web avec HTML5 et CSS3
Apprenez à créer votre site Web avec HTML5 et CSS3Apprenez à créer votre site Web avec HTML5 et CSS3
Apprenez à créer votre site Web avec HTML5 et CSS3
 
Correction de td poo n2
Correction de td poo n2Correction de td poo n2
Correction de td poo n2
 
TD Java POO
TD Java POO TD Java POO
TD Java POO
 
Corrige tp java
Corrige tp javaCorrige tp java
Corrige tp java
 
Ado.net
Ado.netAdo.net
Ado.net
 
Ado .net
Ado .netAdo .net
Ado .net
 
Chapter 3: ado.net
Chapter 3: ado.netChapter 3: ado.net
Chapter 3: ado.net
 

Similar a Getting started with entity framework revised 9 09

Entity Framework Overview
Entity Framework OverviewEntity Framework Overview
Entity Framework Overviewukdpe
 
Entity Framework Overview
Entity Framework OverviewEntity Framework Overview
Entity Framework OverviewEric Nelson
 
What's New for Data?
What's New for Data?What's New for Data?
What's New for Data?ukdpe
 
Entity Framework v1 and v2
Entity Framework v1 and v2Entity Framework v1 and v2
Entity Framework v1 and v2Eric Nelson
 
ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...
ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...
ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...Maarten Balliauw
 
ADO.NET Entity Framework
ADO.NET Entity FrameworkADO.NET Entity Framework
ADO.NET Entity FrameworkHasnain Iqbal
 
ADO.NET Entity Framework
ADO.NET Entity FrameworkADO.NET Entity Framework
ADO.NET Entity FrameworkDoncho Minkov
 
Entity Framework V1 and V2
Entity Framework V1 and V2Entity Framework V1 and V2
Entity Framework V1 and V2ukdpe
 
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
 
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
 
ADO.NET Entity Framework DevDays
ADO.NET Entity Framework DevDaysADO.NET Entity Framework DevDays
ADO.NET Entity Framework DevDaysukdpe
 
Дмитрий Тежельников «Разработка вэб-решений с использованием Asp.NET.Core и ...
Дмитрий Тежельников  «Разработка вэб-решений с использованием Asp.NET.Core и ...Дмитрий Тежельников  «Разработка вэб-решений с использованием Asp.NET.Core и ...
Дмитрий Тежельников «Разработка вэб-решений с использованием Asp.NET.Core и ...MskDotNet Community
 
SQL Data Service Overview
SQL Data Service OverviewSQL Data Service Overview
SQL Data Service OverviewEric Nelson
 
Using Node-RED for building IoT workflows
Using Node-RED for building IoT workflowsUsing Node-RED for building IoT workflows
Using Node-RED for building IoT workflowsAniruddha Chakrabarti
 
Viridians on Rails
Viridians on RailsViridians on Rails
Viridians on RailsViridians
 
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
 
NDC Sydney 2019 - Microservices for building an IDE – The innards of JetBrain...
NDC Sydney 2019 - Microservices for building an IDE – The innards of JetBrain...NDC Sydney 2019 - Microservices for building an IDE – The innards of JetBrain...
NDC Sydney 2019 - Microservices for building an IDE – The innards of JetBrain...Maarten Balliauw
 
Entity Framework Overview
Entity Framework OverviewEntity Framework Overview
Entity Framework OverviewEyal Vardi
 

Similar a Getting started with entity framework revised 9 09 (20)

Getting started with entity framework
Getting started with entity framework Getting started with entity framework
Getting started with entity framework
 
Entity Framework Overview
Entity Framework OverviewEntity Framework Overview
Entity Framework Overview
 
Entity Framework Overview
Entity Framework OverviewEntity Framework Overview
Entity Framework Overview
 
What's New for Data?
What's New for Data?What's New for Data?
What's New for Data?
 
Entity Framework v1 and v2
Entity Framework v1 and v2Entity Framework v1 and v2
Entity Framework v1 and v2
 
ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...
ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...
ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...
 
Ruby On Rails
Ruby On RailsRuby On Rails
Ruby On Rails
 
ADO.NET Entity Framework
ADO.NET Entity FrameworkADO.NET Entity Framework
ADO.NET Entity Framework
 
ADO.NET Entity Framework
ADO.NET Entity FrameworkADO.NET Entity Framework
ADO.NET Entity Framework
 
Entity Framework V1 and V2
Entity Framework V1 and V2Entity Framework V1 and V2
Entity Framework V1 and V2
 
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)
 
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)
 
ADO.NET Entity Framework DevDays
ADO.NET Entity Framework DevDaysADO.NET Entity Framework DevDays
ADO.NET Entity Framework DevDays
 
Дмитрий Тежельников «Разработка вэб-решений с использованием Asp.NET.Core и ...
Дмитрий Тежельников  «Разработка вэб-решений с использованием Asp.NET.Core и ...Дмитрий Тежельников  «Разработка вэб-решений с использованием Asp.NET.Core и ...
Дмитрий Тежельников «Разработка вэб-решений с использованием Asp.NET.Core и ...
 
SQL Data Service Overview
SQL Data Service OverviewSQL Data Service Overview
SQL Data Service Overview
 
Using Node-RED for building IoT workflows
Using Node-RED for building IoT workflowsUsing Node-RED for building IoT workflows
Using Node-RED for building IoT workflows
 
Viridians on Rails
Viridians on RailsViridians on Rails
Viridians on Rails
 
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
 
NDC Sydney 2019 - Microservices for building an IDE – The innards of JetBrain...
NDC Sydney 2019 - Microservices for building an IDE – The innards of JetBrain...NDC Sydney 2019 - Microservices for building an IDE – The innards of JetBrain...
NDC Sydney 2019 - Microservices for building an IDE – The innards of JetBrain...
 
Entity Framework Overview
Entity Framework OverviewEntity Framework Overview
Entity Framework Overview
 

Último

Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 

Último (20)

Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 

Getting started with entity framework revised 9 09

  • 1. Entity Framework @ 5,000 Feet Rob Vettor , C# MVP robvettor@hotmail.com Rob Vettor 1
  • 2. This is Your Life...  You build applications for a living  Each talks to relational database  Learn (at least) 2 different languages (C# and SQL) – Different syntax – Different type systems – Different tools – Different paradigms: Object vs. Procedural  Also must learn the API that binds together: ADO.NET – Powerful, but fragile and time-consuming Rob Vettor 2
  • 3. Here is What You Do… using (SQLConnection conn = new SQLConnection(“<conn string>”); { conn.Open(); SQLCommand cmd = conn.CreateCommand(); cmd.CommandText = “sp_StoredProc”; cmd.parameters.AddWithValue(“@City”, “Dallas”); using (SQLDataReader rdr = cmd.ExecuteReader()) { while (rdr.read()) { string name = rdr.GetString(0); Parameters loosely bound: -- string city = rdr.GetString(1); Strings! No compile Names, types, number of Results are loosely typed } not checked or Intellisense time check until runtime } } Powerful, but fragile and time-consuming Rob Vettor 3
  • 4. Bigger Problem Objects != Relational Data  OO been around for decades; relational databases even longer  Bridging the gap between has been time consuming and expensive: – Legacy ADO.NET Objects Relational Data – Hand-built DALs – 3rd party frameworks  But, the core problem remains! 4
  • 5. So, Now… Instead of building business functionality, Application Database Customer.cs dbo.customer Mapping Code Transform OO to DB Order.cs dbo.order We build plumbing to move data back and forth from data store to business objects. Rob Vettor 5
  • 6. Goals  Fly over the Entity Framework @ 5,000 feet  What it is  What it does  How it works  Why it exists  Test drive examples  Where to find more Rob Vettor 6
  • 7. Autobiographical Stuff…  Architect/Team Lead  C# MVP  INETA Regional Speaker  Frequent Presenter  User Group Leader  Developer Guidance Council member Rob Ve 7
  • 8. Spot Survey  How many use EF in production app?  How many have looked at EF?  How many have looked at LINQ?  How many use Visual Studio 2008?  How many use Visual Studio 2008 and not LINQ? Rob Vettor 8
  • 9. Appeal  Need your feedback and support: – If you like presentation, please send email – Consider lobbying User Group leader to have me present any of the following: – Getting Started with Entity Framework – Getting Started with LINQ – Advanced LINQ – Entity Framework 4.0 – ADO.NET Data Services Rob Vettor 9
  • 10. Agenda s Define Entity Framework s Explore its Architecture s Map Conceptual Model s Program Conceptual Model s Examine Key Concepts s Compare EF vs. L2S s How to get started – Rob Vettor 10
  • 11. What is the Entity Framework? Released in July 2008, EF is a data access framework from Microsoft that helps bridge the gap between data structures and objects in your applications. ADO.NET Evolution “Legacy” ADO.NET ADO.NET Azure RIA 2.0 Data Table Services Services Services Underlying Framework for… Rob Vettor 11
  • 12. What Does It Do? s Develop against conceptual view of your data, instead of data store itself s Automatically generates strongly-typed entity objects that can be customized beyond 1-1 mapping s Automatically generates mapping/plumbing code s Automatically translates LINQ queries to database queries s Automatically materializes objects from data store calls s Automatically tracks changes, generating updates/inserts s Delivers variety of visual modeling tools Rob Vettor 12
  • 13. From a LINQ Perspective Query Operators C# 3.0 VB 9.0 LINQ Proviers LINQ to LINQ to LINQ to LINQ to LINQ to Objects Datasets SQL Entities XML <book> <title/> <author/> <year/> <price/> </book> Objects XML Relational Rob Vettor 13
  • 14. ADO.NET Perspective Entity Framework V3.0 LINQ to Entities, Entity SQL Programming ADO.NET Entity Provider (entity client) Model Conceptual Data Model Mapping Legacy ADO.NET 2.0 does not go away! ADO.NET Data Provider (SqlClient, OracleClient) Reader Connection Store Adapter Command Rob Vettor 14
  • 15. Architectural Layering Object Services Entity Client Core EDM of EF 15 Rob Vettor
  • 16. Entity Data Model s Set of objects that describe structure of your business data and map to your underlying data store Contained in Three XML sections stored in *.edmx file: Database Entity Schema Objects Storage Model Mapping Conceptual Model Database UI OO Services s Abstracts developer from a model pleasing to a DBA (normalized, maintainable, efficient, secure), but complicated to program against Rob Vettor 16
  • 17. Summary s Entity Framework is data access framework that bridges gap between data and objects s Sits beneath many of Microsoft’s new offerings: ADODS, Azure Tables, RIA Services s Automatically creates entity objects and mappings s Transforms LINQ Queries into SQL s Delivers flexible object model that enables you to map data to objects as you like Rob Vettor 17
  • 18. Agenda s The Problem s The EF and EDM sMapping a Conceptual Model… s Programming a Conceptual Model s Key Concepts… s EF vs. L2S s Advanced Mapping s How to get started Rob Vettor 18
  • 19. Map Conceptual Model s Designer Tour…  With mapping wizard, create a new Entity Data Model  Examine entities, scalar and navigation properties in EDM Designer,  Look at the Model Browser  Look at the Mapping Details  Look at the EDMX file  Most importantly, look at generated entity classes s End up with object-representation of our data store s DEMO Rob Vettor 19
  • 20. Mapping Recap Many-to-Many Relationship Represented by navigation Scalar Property Navigation Property Object that describes an that is to related entity. Properties. Suppresses Value Pointer Association, denoted by in Enable app to navigate association entity contained the entity the multiplicity of endpoint to and from. Entity Key domain object distinguished by its identity Rob Vettor 20
  • 21. Agenda s The Problem s The EF and EDM s Mapping a Conceptual Model sProgramming a Conceptual Model… s Key Concepts s EF vs. L2S s Advanced Mapping s How to get started Rob Vettor 21
  • 22. Programing Conceptual Model Two APIs available for coding against EDM Entity Object Client Services s New ADO.NET data provider Query against conceptual model with LINQ  Managed new code generates eSQL s Implements LINQ SQL dialect  SQL  Returns ‘hierarchical’ result set , not tabular Intellisense Compile time type checking, debugging and  Closely resembles ADO.NET, requires connections, s Query results are “materialized” into strongly-typed objects commands, returns data readers s Provides automatic change tracking  Delivers high performance – returns data not objects s Manages concurrency and transactions  Favor when need plain data, not “materialized” entities Rob Vettor 22
  • 23. Two Simple Demos s eSQL Demo… and LINQ-To-Entities Demo…  Query customers from our conceptual model  Return all customers in Oregon  Render in GridView s View generated SQL in SQL Profiler s Demonstrate “Query Syntax” vs. “Method Syntax” s Remember: We are querying conceptual model, not data store Rob Vettor 23
  • 24. Agenda s The Problem s The EF and EDM s Mapping a Conceptual Model s Programming a Conceptual Model sKey Concepts… s EF vs. L2S s Advanced Mapping s How to get started Rob Vettor 24
  • 25. Key Concept: Object Context using (NorthwindEFEntities ctx = new NorthwindEFEntities()) – Workhouse of EF – Entry point to Entity Framework Object – Manages connection to data store Context – Generates SQL queries against store – Marshals data across boundaries and Entity Designer materializes entity objects – Acts as local cache for storing the materialized objects Target Entity – Maintains full change tracking and Uses factory to concurrency management Instantiate entity Rob Vettor 25
  • 26. Associations/Navigation Properties s When generating from database, EF infers <PK><FK> relationships and generates navigation properties  Multiplicity  Direction avigate conceptual model without explicit joins avigation properties, enable us to ‘dot’ into related objects Rob Vettor 26
  • 27. Navigation Properties – From Order, use navigation property to find related OrderDetail entities from o in Order where o.OrderDetails.unitPrice > 20 select o; Order OrderrID <pk> Order maps reference to collection of Order Details objects (EntitySet Type) From OrderDetails, use navigation property to find Order entities from d in OrderDetails where d.Order.orderID == 1 OrderDetail select d; OriderDetailID<pk> OrderD <fk> Order Details maps reference to single Order object (EntityRef Type) s DEMO Rob Vettor 27
  • 28. Projection s Shaping or molding the data returned by LINQ query to include only what you need.  Can project entire sequence from collection…  Can project single value…  Can project selected fields… – Using Concrete Type – Using Anonymous Type… – Builds type on-the-fly – select new { … } (no type name followed by curly braces) – Implements Type Inference… – var keyword tells compiler to infer strong type from right-side expression sDEMO 28
  • 29. Parameterized Queries vs. Sprocs s LINQ fully supports both approaches s Parameterized queries s Good for CRUD operations s Executions plans are cached and reused s Automatically generated by LINQ framework s Do require server permissions at the table level s Stored Procedures s More complex business logic (beyond CRUD) s Security, performance, auditing Rob Vettor 29
  • 30. Deferred Loading s LINQ is built on concept of “deferred execution”  Most query operators don’t execute when declared – //-- First, define query – var query = from c in ctx.Customers s where c.Region == "OR" s orderby c.CompanyName Define query s and store select c; Execute query when in variable s //-- Then, execute query absolutely necessary s gvQuery.DataSource = query; s gvQuery.DataBind();  Query gets executed when enumerated – Bound to a DataBound control – Execute within ForEach loop Iteration – Transformed to collection ToList(), ToArray(), etc Rob Vettor 30
  • 31. Eager Loading s Force LINQ to immediately execute query  Operators that return a singleton: – Aggregate Methods – Element Methods – Retrieve specific element from sequence – First(), Last(), ElementAt()  Collection-Conversion Operators – ToArray(), ToList(), ToDictionary(), ToLookup() s Include() method supports eager execution:  Retrieves parent and child entities immediately, not when referenced s (No Demo Yet) Rob Vettor 31
  • 32. Loading Single Objects s Basic Example – Run SQL Profiler and step thru code – Demonstrate Deferred and Eager loading – Explore when execution takes place – See how each enumeration of same query generates a separate call to DB s DEMO NOW! Rob Vettor 32
  • 33. Loading Object Graphs s Object Graph: Set of individual, but related objects, that together form a logical whole unit Customer Order Order Detail Product Category s By default, with deferred execution, child objects load one at a time (separate data store call for each) as needed. s We can use Include() method to predefine the object graph, forcing all entire graph to load at once with single query s DEMO  Load object graph including Orders, Order Details and Products Rob Vettor 33
  • 34. Deferred vs. Immediate  Deferred Execution – Benefits: – Fetches data only when needed, not all at once – Minimize network traffic, memory consumption and load on database – Great for when can but fetch objects as user requests them – Drawbacks: – Chatty Interface: Each request for child record invokes explicit database query Rob Vettor 34
  • 35. Deferred vs. Immediate  Immediate Execution – Benefits: – Singe query returns all data – Great if you know that you will need all data returned – Drawbacks: – Large amount of data returned, whether used or not. Rob Vettor 35
  • 36. Updates/Change Tracking s ObjectContext automatically tracks changes to entities via the ObjectStateManager object  Upon retrieval, caches original values  Tracks any changes made to entities  Dynamically constructs update/insert SQL statements – If not updating an entity, disable Change Tracking – ctx.Products.MergeOption = MergeOption.NoTracking; s Next DEMO  Demonstrate change tracking  Update postal code and freight charge for an order  Watch ObjectStateManager track both changes and original values  See it generate parameterized SQL update statement  Explicitly wrap in transaction Rob Vettor 36
  • 37. Inserts s Inserting with EF is multi-step process s Create new (disconnected) entity object and populate s Attach new entity to the ObjectContext s Call SaveChanges() to commit to database s Next DEMO s Show how ObjectContext leverages inferred relationship s Inserts both parent and child records in correct order s Maintains foreign key relationship s Automatically manages the identity values s Show that ObjectContext automatically returns new identity key and assigns to new entity objects Rob Vettor 37
  • 38. Agenda s The Problem s The EF and EDM s Mapping a Conceptual Model s Programming a Conceptual Model s Key Concepts sEF vs. L2S… s Advanced Mapping s How to get started Rob Vettor 38
  • 39. History s On the surface, appear to look and behave closely  LTS – Evolved from LINQ Project, a language-development team  EF – Evolved from Data Programmability Team (DPT) which initially focused on the Entity SQL language – Later adapted LINQ to work with entity objects s LTS later moved to the Data Team s 11/08, Data Team announced invest in EF, while maintaining and tweaking L2S s Microsoft will provide migration path to EF and recommend EF over LTS 39
  • 40. How They Differ s General consensus:  LTS – Strongly typed LINQ access for RAD against SQL Server only – Support s only direct Table-Per-Type (1-to-1) mapping – Limited out-of-the box support for complex scenarios  EF – Designed for larger enterprise applications – Enables complex mapping complex scenarios – Tools and designer more robust – Supports inheritance and many-to-many relationships – Supports provider independence 40
  • 41. EF vs. LTS Category LINQ to SQL Entity Framework Model domain model conceptual data model Databases Supported SQL server only Many Complexity/Learning Curve simple to use complex to use slower development but more Development Time rapid development capabilities Mapping Direct 1-to-1 Custom mapping Inheritance hard to apply simple to apply Support ? $$$, resources, innovation Rob Vettor 41
  • 42. Agenda s The Problem s The EF and EDM s Mapping a Conceptual Model s Programming a Conceptual Model s Some Intermediate Topics s EF vs. L2S sAdvanced Mapping… s How to get started Rob Vettor 42
  • 43. Advanced EDM Mapping s EDM provides flexibility customizing conceptual model s Most customizations occur in the conceptual model and depend on the mapping layer to map to underlying store s Designer supports following customization:  Table Per Hierarchy Inheritance mapping  Table Per Type Inheritance mapping  Entity (vertical) splitting Rob Vettor 43
  • 44. Mapping Between Layers Logical Schema Table Per Type Inheritance Conceptual Schema Contact SalesPeople Employee SalesPerson SalesOrder SalesOrder StoreOrder Table Per Hierarchy Inheritance Storage Schema Mapping Con. Schema .ssdl File .msl File .csdl File Rob Vettor 44
  • 45. Table-Per-Hierarchy Mapping (TPH) s Simple inheritance that maps multiple entities to single database table s Mapping conditionally based on discriminator column to differentiate records as different types s Quick to implement, but lacks scalability – derived from single database table Base Type Entities Discriminator Column Database Table Employee Employee managementFlag ManagementEmployee s No Demo Yet Derived Type Rob Vettor 45
  • 46. Using TPH s Discriminator column identifies whether row belongs to base or derived type s Can include additional columns for derived type whose value is NULL for base type (denormalized!) s Can query on derived types without a where clause by using OfType() method  from c in ctx.Customers.OfType<ManagementEmployees>() s Show in Designer s Demo s Limitations  Difficult to update discriminator column value via EF – must use database construct (trigger/stored proc) Rob Vettor 46
  • 47. Table-Per-Type Mapping s Inheritance spanning related database tables. s Exposes attributes from both parent table and child table into single derived entity s Defined in database with separate tables where one table (child) describes new type based on another table (parent) Database Table Entities Customers Tax Audit State Tax Audit CustomersUSA s No Demo Yet Rob Vettor 47
  • 48. Using TPT s Eliminates need to programmatically traverse navigation properties to move from child (CustUSA) to parent (Cust) to include parent information s When projecting on derived type, use OfType() method  from c in ctx.Customers.OfType<CustomersUSA>() s Show in Designer, Demo s Limitations:  Derived type is completely bound to parent type – cannot directly access derived type; only thru parent  Cannot delete child without deleting parent  Cannot change existing customer to CustomerUSA Rob Vettor 48
  • 49. Entity (Vertical) Splitting s Map single entity to multiple tables s Tables must share common key s Typically for 1-to-1 relationships where one table provide additional information about another Database Tables Employee Entities EmployeeFinancial Employee EmployeePersonal s No Demo Yet Rob Vettor 49
  • 50. Using Entity (Vertical) Splitting s Vertical Entity Partitioning s Addresses data modeling practice of decomposing large table into number of smaller tables s Relives you from having to traverse navigation properties among the tables to retrieve data s In mapping details window, we map single entity to three underlying tables s Conceptual model contains single product entity s Store (SSDL) contains three product tables s MSL metadata maps single entity to multiple tables Show Mapping Details in Designer; Demo Rob Vettor 50
  • 51. Advanced EDM Mapping s EDM enables you to decouple and customize your conceptual layer and design it to align more with your business processes, rather than the highly-normalized design a DBA might create s The Mapping Detail Tool enables you to map your customizations to your underlying data store layer s Designer supports most, but not all, customization  Table Per Hierarchy Inheritance mapping  Table Per Type Inheritance mapping  Entity (vertical) splitting Rob Vettor 51
  • 52. Agenda s The Problem s The EF and EDM s Mapping a Conceptual Model s Programming a Conceptual Model s Key Concepts s EF vs. L2S s Advanced Mapping sGetting Started… Rob Vettor 52
  • 54. EF Webcasts s Mike Taulty  150 Screen Casts Rob Vettor 54
  • 55. Questions? Comments? Suggestions? robvettor@hotmail.com http://weblogs.asp.net/dotnetarchitect Rob Vettor 55

Notas del editor

  1. Today, with ADO.NET 2.0, We have providers that provide connections, commands, etc that are specific to a particular data store In Version 3.0, developer can build conceptual model of the store Program against model that ties closely to domain Mapping technology translates conceptual model to real store You are abstracted from underlying store and program against conceptual model instead of logical model LINQ to Entities is object-relational mapping API mapping between conceptual model and .NET types in memory, which give you the ability to use language integrated queries to manipulate the conceptual model So. in nutshell, on top you have LINQ, with Object Relational Mapping API on top of a conceptual model, which itself is mapped to is mapped to the underlying store.