This document provides an overview of Entity Framework 4. It begins with an introduction to Entity Framework and the benefits it provides such as decreased code and maintenance for data applications by programming against a conceptual model rather than a relational schema. It then covers references, getting started by demonstrating how to set up an Entity Data Model, modeling approaches, querying the database using LINQ, using stored procedures and functions, working with Plain Old CLR Objects (POCOs), loading related entities, potential gotchas, and concludes with asking if there are any questions.
2. Overview
Introduction
References
Getting started
Modeling
Queries
Stored Procedures
Functions
POCO
Loading related entities
Gotchas
Questions
3. ADO.NET Entity Framework
The ADO.NET Entity Framework enables developers to create data access
applications by programming against a conceptual application model
instead of programming directly against a relational storage schema. The
goal is to decrease the amount of code and maintenance required for data-
oriented applications. Entity Framework applications provide the following
benefits:
Applications can work in terms of a more application-centric conceptual
model, including types with inheritance, complex members, and
relationships.
Applications are freed from hard-coded dependencies on a particular
data engine or storage schema.
Mappings between the conceptual model and the storage-specific
schema can change without changing the application code.
Developers can work with a consistent application object model that can
be mapped to various storage schemas, possibly implemented in different
database management systems.
Multiple conceptual models can be mapped to a single storage schema.
Language-integrated query (LINQ) support provides compile-time syntax
validation for queries against a conceptual model.
4. References
ADO.NET Entity Framework on MSDN
Brian Mains (2011), Demystifying Entity
Framework 4 - A hands-on introduction to
working with ADO.NET Entity Framework
Larry Tenny & Zeeshan Hirani (2010), Entity
Framework 4.0 Reciepes: A Problem-
Solution Approach, Apress
John Papa (2007), ADO.NET Entity
Framework Overview
7. Terminology
EntityType - The specification for a data type that includes a key and a named
set of properties and represents a top-level item in a conceptual model or
storage model.
EntitySet - A logical container for entities of a given type and its subtypes.
Entity sets are mapped to tables in a database.
Association - The definition of a relationship between entity types.
Navigation Property - A property of an entity type that represents a
relationship to another entity type, as defined by an association.
ComplexType - The specification for a data type that represents a non-scalar
property of an entity type that does not have a key property. A ComplexType
is typically used to group related properties together in a model.
POCO entity - An entity in the Entity Framework that does not inherit
from EntityObject or ComplexObject and does not implement the Entity
Framework interfaces. Frequently, POCO entities are existing domain objects
that you use in an Entity Framework application. These entities support
persistence ignorance.
Persistence-ignorant Object - An object that does not contain any logic that is
related to data storage. Also known as a POCO entity.
8. Modeling
Fundamentals:
Modeling – Designing and creating a
conceptual representation of a new or
existing storage schema
Can be done one of three ways
Database First
Model First
Code First
10. Queries
LINQ
Extensions to the .NET Framework that allow
traversal, filtering and projection operations in a
direct yet declarative way
Entity SQL
Similar to T-SQL; allows querying entity data as
objects or in tabular form; requires EntityClient
Provider
Entity SQL Builder
Similar to LINQ; A set of ObjectQuery methods and
extension methods that allows a way to load and
return lists of objects directly. Like LINQ provides a
way to navigate objects and their relationships; can
use Entity SQL or LINQ to execute queries
12. Stored Procedures
Stored Procedures - Code that runs on the
database server which abstracts the
details of the physical organization of data
Added to the Storage Layer from the
database using the designer
Not immediately exposed through the
model; the model requires the creation of
a function import (method) that represents
the sproc and its inputs/outputs
13. Functions
Functions – Existing code used for
performing calculations on data
Three types of functions:
Model defined functions
Entity Framework defined functions
Database Layer defined functions
15. POCO
POCO (Plain Old CLR Objects) - A custom class
(domain object) used as entities in a model
Don’t contain any reference to specialized
frameworks
Don’t need to derive from third-party code
Don’t need to implement any special interface
Don’t need to live in any special assembly or
namespace. You implement your domain objects
however you see fit
Commonly used with popular architectural patterns
such as Repository Pattern
Requires Custom Object Context; auto generated
code feature is turned-off
Very finicky!!!
16. Loading Related Entities
Related entities are defined through
associations/navigation properties
Can be explicitly or implicitly (lazy loading)
loaded
18. Gotchas
Modeling
Can result in Run-time errors if relationships are not
modeled properly
There are certain pre-requisites that must be met
when defining relationships; usually result in
compilation errors
POCOs
Properties in POCOs are case sensitive
They must be identical to the case and spelling of
the objects they are mapped to in the Storage
Layer; must include all columns/properties
Can cause run-time errors or can result in no data
returned from database
For example, in a conventional database-oriented system, entries about a customer and their information can be stored in a Customer table, their orders in an Order table and their contact information in yet another Contact table. The application that deals with this database must "know" which information is in which table, i.e., the relational schema of the data is hard-coded into the application.The disadvantage of this approach is that if this schema is changed the application is not shielded from the change. Also, the application has to perform SQL joins to traverse the relationships of the data elements in order to find related data. For example, to find the orders of a certain customer, the customer needs to be selected from the Customer table, the Customer table needs to be joined with the Order table, and the joined tables need to be queried for the orders that are linked to the customer.This model of traversing relationships between items is very different from the model used in object-oriented programming languages, where the relationships of an object's features are exposed as Properties of the object and accessing the property traverses the relationship.
Add’l references not used for this presentation:Julia Lerman (2010), Programming Entity Framework 2nd Ed, O’Reilly -- This book is highly recommended!!!http://blogs.msdn.com/b/adonet/ -- This is where many of the prominent developers in the community involved with EF get their information on
The EDM definesthe data types, the specific definitions of what types of relationships are allowed, the schemas thatsupport the model, and the mapping between these schemas.The EDM should be considered a Class and the individual Models (the tables, views, sprocs) should be considered Instance ClassesThe conceptual layer, or conceptual model, is perhaps the only part many developers see when theywork with a model. Visual Studio provides a full-featured designer that enables you to whiteboard thehigh-level nouns (entity types) and relationships (associations) in our domain. On the conceptual layer,there is no taint of a physical storage organization. With the designer you create entities, perhapsestablish inheritance hierarchies, and link entities together through associations. The syntax for theconceptual model is defined by the Conceptual Schema Definition Language (CSDL).Every useful application needs to persist objects to some data store. The store layer, or store model,defines the data store. This includes the tables, columns, and data types that the EntityClient layer willultimately map to the underlying database. The syntax for the store model is defined in by the StoreSchema Definition Language (SSDL).The mapping between the conceptual model and the store model is defined by the mapping layer.Among other things, this layer defines how properties on entities map to columns on tables. Although itis tucked away in the Mapping Details window, this mapping layer is also exposed to the developer through the designer. The syntax for the mapping layer is defined by the Mapping SpecificationLanguage (MSL).
Create a sample project:Open a new instance of VSCreate new MVC3 ProjectCompile and run the projectAdd the EF Project to the Model Directory – Add the Orders, OrderDetails and Product TablesShow ModelBrowser Conceptual Layer, Storage Layer and Mapping LayerShow Designer.cs file
Modeling – Designing and creating a conceptual model of a storage schemaDatabase First – Designer-centric option of modeling. Also ships with release of Entity 4. The most common option for modeling; EF creates entities for you based on an existing storage schema. Supports changes to the database since the database defines the storage schema and domain model of your application. Model First – Designer-centric option of modeling. EF’s “model first development” ships with release of Entity 4. Uses designer to draw your conceptual model and generate your storage schema using generated scripts. Does not support manual changes to the database since model defines schema. Code First – Code-centric option of modeling. EF’s “code first development” support is currently enabled with a separate download that runs on top of the core EF built-into .NET 4; no need to configure any additional database schema mapping information, nor run any tools, nor edit any XML files, nor use any designers in order to start using business objects (classes) to retrieve, update, and save data into a database. Database schema can either be manually created or automatically generated. Does not support manual changes to the database since application code defines schema.
Create a sample project:Open a new instance of VSCreate new Console ProjectAdd an EDM from existing databaseRun a queryExplain RelationshipsCreate a new relationship from the views
There are essentially basically three ways to query the database. LINQ, Entity SQL and Entity SQL Builder. Most devs will probably use a combination of LINQ and Entity SQL Builder depending on the needs of the application.LINQ – (AKA LINQ to Entity) LINQ is a set of extensions to the .NET Framework that encompass language-integrated query, set, and transform operations. LINQ is an integrated feature of the developer's primary programming language. The standard query operators can be applied to collections of IEnumerable<T> and allow traversal, filter, and projection(selecting specific data w/o retrieving all fields) operations to be expressed in a direct yet declarative way.Entity SQL – (AKA EntityClient) Entity SQL is Entity SQL is a storage-independent query language that is similar to SQL. Entity SQL allows you to query entity data, either as objects or in a tabular form. You should consider using Entity SQL in the following cases:If you are already an expert in SQL-based query languages, Entity SQL may seem the most natural to you.When a query must be dynamically constructed at runtime. In this case, you should also consider using the query builder methods of ObjectQuery instead of constructing an Entity SQL query string at runtime.When you want to define a query as part of the model definition. Only Entity SQL is supported in a data model. For more information, see QueryView Element (MSL).When using EntityClient to return read-only entity data as rowsets using a EntityDataReader. For more information, see EntityClient Provider for the Entity Framework.Entity SQL Builder – (AKA ObjectQuery, Object Services) A set of ObjectQuery methods and extension methods that provides a way to load objects and navigate any relationships defined in the EDM. You can use Object Services to execute queries using Entity SQL or you can write queries using LINQ to Entities. Entity SQL Builder Features:Identity resolution (w/ entity keys (PK/FK) – process done manually with datasets) Provides object persistence and change tracking through events to allow an explicit load and save reducing trips to the server.Allows lists of objects to be returned directly—both projections and defined entities can be returned. Note: If you use projections with Object Services, the data returned will not be an updateable object. Because projections return specific properties of entities and not the entire entity, Object Services cannot save updates to the projected data back to the database. If you intend to update the data, a better option is to return the entire entity rather than using a projection. Consider using Entity SQL (EntityClient) or Entity SQL Builder with ObjectDataSource (this is “a way” – I’m sure there are many others).Using Aliases with ObjectQuery - In a query builder method, you refer to the current ObjectQuery command by using an alias. By default, the string "it" is the alias that represents the current command
Code LINQ example to show benefits of LINQ and IntellisenseExplain and then run ESQL and ESQL Builder Examples to compare data returned – all results should be the same
In the context of EF, what are stored procedures and what are they used for?
In the context of EF, what are functions and what are they used for?There are three types of functions:Model defined functions - Allow you to create functions at the conceptual layer; are defined in terms of Entity Framework types and your model entities.Entity Framework defined functions – Existing functions defined by the Entity FrameworkDatabase Layer defined functions – Existing functions defined by the database
Create new console projectAdd EDM from existing DbAdd a SprocQuery SprocAdd a regular table and query table using Entity Function
POCOs are custom classes (domain or business objects) used as entities in a model.Characteristics of POCO:Don’t contain any reference to specialized frameworks Don’t need to derive from third-party codeDon’t need to implement any special interfaceDon’t need to live in any special assembly or namespace. You implement your domain objects however you see fitCommonly used with popular architectural patterns such as Repository PatternRequires Custom Object Context; auto generated code feature is turned-offVery finicky!!! – Properties in POCOs are case sensitive. They must be identical to the case and spelling of the objects they are mapped to in the Storage Layer. They are also prone to problems if entity relationships are not modeled correctly.
A technique – Go with Lazy Loading first and if necessary explicitly load entitiesExplicit loading may be necessary for optimizing data returned from the database