2. Intro to Entity Framework (Recon)

Intro to Entity Framework
A Reconnaissance
(No Driving Yet)
Tom Perkins
• Last Session:
– We created a small Entity Framework application stepby-step and
– displayed data in a GridView from a database.
• This Session:
– We’ll again create a small Entity Framework
– We’ll look at the components in more detail for the
purpose of gaining familiarity with what the
Framework produces.
• Work along or watch!
A Different Programming Perspective
Entity Data
Focus on business objects
Data Store
Focus on tables, stored
Procedures, views, etc.
EDM is a “concept”
Entity Data Model
Implemented as:
Design time
Run time
3 XML Files
XML Files
Design Time
Entire Model
Run Time
Entity Data
Model Schema
Objects Schema
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
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
Name: Chapter2ConsoleApp
Location: (use default)
Solution: ProgrammingEntityFramework
Click OK
•Right-click on Chapter2ConsoleApp in the Solution Explorer
•Add | New Item
Select ADO.NET Entity Data Model from the Templates list | Add
Select Generate from database | Next
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
Select Tables, Views | Change Model Namespace to
SampleModel | Finish
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.
 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
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
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
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.
-- XML –
XML Files
Design Time
Entire Model
Run Time
Entity Data
Model Schema
Objects Schema
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
• Physical files stored in project assembly at
compile time (you won’t see them).
The Model Browser
• Right-click on the design surface
• Choose Model Browser from the context menu.
• Gives another view of the metadata.
• 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.)
Raw XML in the Designer
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:
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
Expanded Schema and Entity
Container nodes
The above XML is the source of the graphical display we saw in the Designer.
Model Elements We’ll Examine
Entity Container
Entity Set
Entity Type
The Key Element
Property Elements
Navigation Property
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
The Entity Container
Contact Object
Contact Object
Entity Container
Contact Object
Address Object
Address Object
LazyLoading  Annotation  used as directions for generation of code
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" />
The Entity Type
<EntityType Name="Address">
<PropertyRef Name="addressID" />
<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" />
Key element: Identity key for entity; may be composite
tracks entity, helps perform updates and refreshes, very important
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
<Association Name="FK_Address_Contact">
<End Role="Contact"
<OnDelete Action="Cascade" />
<End Role="Address"
Multiplicity="*" />
<Principal Role="Contact">
<PropertyRef Name="ContactID" />
<Dependent Role="Address">
<PropertyRef Name="ContactID" />
Defines relationships
between entity types
Describes “end points” of
relationship and
multiplicity (1, 0..1,*)
Cascade – if Contact is
deleted, delete associated
Let’s look at the view in
the Designer … Close the
XML and double-click on
the Model1.edmx in the
Solution Explorer.
FK_Address_Contact Association
Defines relationships between
entities – Contact and Address
Focuses on “endpoints”
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
Role – Address
Multiplicity – many addresses per contact
Association Set – may be more than one
per entity
Referential Constraint
For Foreign Keys
Shows dependency between related entities
Every Address must have a Contact
Used to maintain integrity of database
Address_Contact Navigation Property
Shows how to navigate to associated
Association – how to navigate to
associated entity (or entities)
From Role, To Role – navigate from
Address to Contact
Multiplicity – returns 1 Contact object
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
• Simple model
• Conceptual Layer mirrors the database
• Customizing the model (later) gives real power
to Entity Framework
Expanded StorageModels Section
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
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
– Right Click on Contact Entity
– Select Table Mapping
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
Database Views: vOfficeAddress
• Note: DefiningQuery
Introduced you to EDM and design tools
Created an EDM
Looked under the hood
Enough to get started with Querying
Stay tuned for more exciting developments

similar documents