1 / 49

Intro to Entity Framework

Intro to Entity Framework. A Reconnaissance (No Driving Yet) Tom Perkins. Objectives. Last Session: We created a small Entity Framework application step-by-step and displayed data in a GridView from a database. This Session: We’ll again create a small Entity Framework application.

benoit
Download Presentation

Intro to Entity Framework

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Intro to Entity Framework A Reconnaissance (No Driving Yet) Tom Perkins

  2. Objectives • Last Session: • We created a small Entity Framework application step-by-step and • displayed data in a GridView from a database. • This Session: • We’ll again create a small Entity Framework application. • We’ll look at the components in more detail for the purpose of gaining familiarity with what the Framework produces. • Work along or watch!

  3. A Different Programming Perspective bridge Entity Data Model (EDM) Application Data Store Focus on business objects Focus on tables, stored Procedures, views, etc. Developer

  4. EDM is a “concept” Entity Data Model (EDM) Implemented as: Design time Run time 3 XML Files EDMX File

  5. XML Files Design Time Run Time Entire Model *.EDMX Entity Data Model Schema Compile *.CSDL Mappings *.MSL Database Objects Schema *.SSDL

  6. What Entity Framework Does • Generates classes from model • Updates classes as model changes • Handles database connectivity • Querying done on model, not database • Translates queries into database queries • Tracks changes to objects in the model • Handles updates to the database

  7. Build a simple EDM • Sample database, ProgrammingEFDB1 • 2 tables, one view, some stored procedures • Create a new Console Application In VS2010, File | New | Project Select Console Application

  8. Name: Chapter2ConsoleApp Location: (use default) Solution: ProgrammingEntityFramework

  9. Click OK

  10. Right-click on Chapter2ConsoleApp in the Solution Explorer • Add | New Item

  11. Select ADO.NET Entity Data Model from the Templates list | Add

  12. Select Generate from database | Next

  13. Make sure your local SQL Server is active Set up a new connection if necessary Change the App.Config settings name to “Sample Entities” | Next

  14. Select Tables, Views | Change Model Namespace to SampleModel | Finish

  15. New model appears. Note Model1.edmx file. • To display the model at any time, double-click on the Model1.edmx file in the Solution Explorer.

  16. The designer window

  17. Gives a graphical view of the EDM and its members. • Contact Entity, Address Entity, and vOfficeAddressEntity • 2 from DB Tables, one from View • connecting line  One-to-Many relationship  associations • Scalar properties (ContactID, FirstName, etc) • Navigation properties (Addresses, Contact) – Addresses property enables navigation from Contact Entity to set of Addresses related to that contact

  18. Using the Properties Window • A logical group of entities  entity container • Click in the white space of the Designer Window, then look at the Properties window. • You can modify the Entity Container Name and the Namespace • You can set whether to pluralize new objects or not

  19. The Properties of an Entity • Click on the Contact Entity • Entity name: Contact  db table • Entity Set Name pluralized • Entity names should be singular • Entity set  a container for entities of a single type

  20. The Properties of an Entity Property • Click on Contact’s FirstName property • FirstName is a non-nullable string with a maximum length of 50 characters, variable. • It is not the Entity key. • The framework does not perform validation of the Max Length, Unicode, and Fixed Length properties. These properties are ignored.

  21. The raw format of the model-- xml –supporting metadata

  22. XML Files Design Time Run Time Entire Model *.EDMX Entity Data Model Schema Compile *.CSDL Mappings *.MSL Database Objects Schema *.SSDL

  23. Supporting Metadata • Sections • ConceptualModels • StorageModels (db schema) • Mappings • Last 2 tell how to translate between conceptual model and actual data store • Mapping – translates entities and properties (conceptual model) to tables and columns (StorageModel) • Physical files stored in project assembly at compile time (you won’t see them).

  24. The Model Browser • Right-click on the design surface • Choose Model Browser from the context menu. • Gives another view of the metadata.

  25. Raw XML • Only a portion of the model is visible in the Designer. • View complete model in XML form. • To see the raw format of the model: • In Solution Explorer • Right-click on Model1.edmx file • On context menu • Select “Open With” • Choose XML Editor • Click OK • (Only one view of the model at a time is allowed – click OK to close the Design View of the model when prompted.)

  26. Raw XML in the Designer

  27. Model with Sections Collapsed • To collapse the model • Right-click on XML • Choose Outlining • Toggle All Outlining • Expand nodes to get the main sections of the model:

  28. CSDL: The Conceptual Schema • If a line loses its hard returns, • Highlight the line • From VS Menu, select Edit | Advanced | Format Selection to format the line • In ConceptualModels section, Click on + icons to expose the Schema and EntityContainer

  29. Expanded Schema and Entity Container nodes The above XML is the source of the graphical display we saw in the Designer.

  30. Model Elements We’ll Examine • Entity Container • Entity Set • Entity Type • The Key Element • Property Elements • Associations • Navigation Property

  31. The Entity Container • Name: • Defaults from model name • Change in model’s Property Window • Wrapper for Entity Sets and Association Sets • Exposes Entity Sets • You write queries against these

  32. The Entity Container Contact Object QUERY Contact Object Contact Object Entity Container Contacts Addresses Address Object Address Object LazyLoading Annotation  used as directions for generation of code

  33. The Entity Set • Gives access to individual entities when querying against model • Example: “find some entities in the Contact EntitySet”  returns some Contact Entity Types • Entity Type: Strongly Typed Name for Entity <EntitySet Name="Addresses" EntityType="SampleModel.Address" /> <EntitySet Name="Contacts" EntityType="SampleModel.Contact" /> <EntitySet Name="vOfficeAddresses" EntityType="SampleModel.vOfficeAddress" />

  34. The Entity Type • <EntityType Name="Address"> • <Key> • <PropertyRef Name="addressID" /> • </Key> • <Property Name="addressID" Type="Int32" Nullable="false" annotation:StoreGeneratedPattern="Identity" /> • <Property Name="Street1" Type="String" MaxLength="50" Unicode="true" FixedLength="false" /> • <Property Name="Street2" Type="String" MaxLength="50" Unicode="true" FixedLength="false" /> • <Property Name="City" Type="String" MaxLength="50" Unicode="true" FixedLength="false" /> • <Property Name="StateProvince" Type="String" MaxLength="50" Unicode="true" FixedLength="false" /> • <Property Name="CountryRegion" Type="String" MaxLength="50" Unicode="true" FixedLength="false" /> • <Property Name="PostalCode" Type="String" MaxLength="50" Unicode="true" FixedLength="false" /> • <Property Name="AddressType" Type="String" Nullable="false" MaxLength="50" Unicode="true" FixedLength="false" /> • <Property Name="ContactID" Type="Int32" Nullable="false" /> • <Property Name="ModifiedDate" Type="DateTime" Nullable="false" /> • <NavigationProperty Name="Contact" Relationship="SampleModel.FK_Address_Contact" FromRole="Address" ToRole="Contact" /> • </EntityType> Key element: Identity key for entity; may be composite tracks entity, helps perform updates and refreshes, very important

  35. Property Elements • Can’t have XML and Designer open at the same time • Close XML view, double-click .edmx file to view an element’s properties • Not all propertes appear in XML , but do appear in Properties window • Currency mode, default value, Getter, Setter • “Facets” are used to describe properties

  36. Association • Defines relationships between entity types • Describes “end points” of relationship and multiplicity (1, 0..1,*) • Cascade – if Contact is deleted, delete associated Addresses • Let’s look at the view in the Designer … Close the XML and double-click on the Model1.edmx in the Solution Explorer. <Association Name="FK_Address_Contact"> <End Role="Contact" Type="SampleModel.Contact" Multiplicity="1"> <OnDelete Action="Cascade" /> </End> <End Role="Address" Type="SampleModel.Address" Multiplicity="*" /> <ReferentialConstraint> <Principal Role="Contact"> <PropertyRef Name="ContactID" /> </Principal> <Dependent Role="Address"> <PropertyRef Name="ContactID" /> </Dependent> </ReferentialConstraint>

  37. FK_Address_Contact Association • Defines relationships between entities – Contact and Address • Focuses on “endpoints” • End1 • Contact • Assigned “role” – Contact • Also name that can be used in model to point to this end • Multiplicity (only one Contact) • Navigation – other end of association • Cascade – delete addresses if contact is deleted • End2 • Role – Address • Multiplicity – many addresses per contact • Association Set – may be more than one per entity

  38. Referential Constraint • For Foreign Keys • Shows dependency between related entities • Every Address must have a Contact • Used to maintain integrity of database

  39. Address_Contact Navigation Property • Shows how to navigate to associated entity • Association – how to navigate to associated entity (or entities) • From Role, To Role – navigate from Address to Contact • Multiplicity – returns 1 Contact object

  40. Contact.Addresses Navigation • This Navigation Property returns a collection of addresses • No address for Contact, collection will be empty • “Type” is a special EntityCollection, not type implementing System.Collections.ICollection(not interchangeable)

  41. This CDSL • Simple model • Conceptual Layer mirrors the database schema • Customizing the model (later) gives real power to Entity Framework

  42. Ssdl (Storagemodel section)

  43. Expanded StorageModels Section

  44. StorageModels Section • Provides a description of the data store (database) • Tables called Type, Columns called Property • “Store” is in Namespace to minimize confusion • ProviderManifestToken – version of SQL Server • You must modify manually if switching to SQL Server 2005 • Entity container – derived from db name • Entity Type – name of table • Property types – SQL Server data types • Identity column – StoreGeneratedPattern=“Identity” – identity value generated by db when row is inserted, will not change • Other options • “Computed” – values generated • “None” - default

  45. Msl: Mapping from conceptual Model to storage (and Back)

  46. MSL: Mappings Section • Logically between concept and storage models • Maps entity properties back to tables and columns of data store • Enables further customization of model • Use the Mapping Details Window • (Close XML view) Open Designer (dbl-clk on .edmx) • Right Click on Contact Entity • Select Table Mapping

  47. Mapping Details Window • Maps Contact entity to Contact table • Maps to Contact  Contact table in SSDL • Here, one to one relationship – can be customized • When you create mappings, wizard matches names for you • Note SQL data types

  48. Database Views: vOfficeAddress • Note: DefiningQuery

  49. Summary • Introduced you to EDM and design tools • Created an EDM • Looked under the hood • Raw XML • Mappings • Enough to get started with Querying • Stay tuned for more exciting developments

More Related