You are on page 1of 23

ADO.

NET Entity
Framework 4.0
Claeys Kurt

CodeCamp.NL
Hi !
• CLAEYS Kurt
– .Net Solution Architect ORDINA.BE
– Community Geek (Visug.be, AZUG.BE)
– Focus on WCF/ADO.NET/Azure/.NET services
– MCT Trainer
– MVP Connected System Developer
– MCSD + MCTS Biztalk/WCF/WF/ADO.NET 3.5
– Mail : Kurt.Claeys@casey.be
– Blog : www.devitect.net

I’m from Belgium !


Eh ... From where ?
Agenda (1.15’)

• What is ORM ?
• ADO.NET Entity Framework
• Some patterns
• Code examples & demos
• New in EF 4.0
• More code !
Object – Relational Mapping
Conceptual Mapping Storage

*
*

Objects Relations
Architecture

EF
.NET Entity Provider
Programming (Entity SQL)
Model
Conceptual Model
Quering with LINQ Reader
or Entity SQL Connection
Entity Entity
relationship Command
Updating through the ObjectContext

Mapping (MSL)
V2.0

.NET Data Provider


Reader Connection
Store
Adapter Command
3 Layers
Conceptual layer(CSDL)

The conceptual entity model that represents the entities and


their associations and inheritance structure = Domain Model

Mapping layer(MSL)

The metadata needed to map the conceptual model to the


logical model.

Storage layer (SSDL)

The logical store model that represents the relational schema


from a database
Storage Layer

<EntityType Name="Employees"> Tables + PK


<Key>
SQL
<PropertyRef Name="EmployeeID" />
Field and Types
</Key>
<Property Name="Address" Type="nvarchar" MaxLength="60" />
...
<Property Name="TitleOfCourtesy" Type="nvarchar" MaxLength="25" />
</EntityType>

<ReferentialConstraint>
<Principal Role="Employees"> PK/FK relations
<PropertyRef Name="EmployeeID" />
</Principal>
<Dependent Role="EmployeesTerritories">
<PropertyRef Name="EmployeeID" />
</Dependent>
</ReferentialConstraint>
Conceptual Layer
<EntitySet Name="Categories"
EntityType="NORTHWINDEFModel.Categories" />
... Associations
<AssociationSet Name="FK_Products_Categories"
Association="NORTHWINDEFModel.FK_Products_Categories">
<End Role="Categories" EntitySet="Categories" />
<End Role="Products" EntitySet="Products" />
</AssociationSet>

<EntityType Name="Categories">
Entities / Keys
<Key>
<PropertyRef Name="CategoryID" /> .NET Types
</Key>
<Property Name="CategoryID" Type="Int32" Nullable="false" />
<Property Name="CategoryName" Type="String" Nullable="false“ />
<NavigationProperty Name="Products"
Relationship="NORTHWINDEFModel.FK_Products_Categories"
FromRole="Categories" ToRole="Products" />
</EntityType>
Mapping Layer
Inheritance
<EntityTypeMapping
TypeName="IsTypeOf(NORTHWINDEFModel.DiscontinuedProducts)">
<MappingFragment StoreEntitySet="Products">
<ScalarProperty Name="UnitsOnOrder" ColumnName="UnitsOnOrder" />
<ScalarProperty Name="UnitsInStock" ColumnName="UnitsInStock" />
...
<Condition ColumnName="Discontinued" Value="true" />
</MappingFragment>
</EntityTypeMapping>
Discriminators
TPC Mapping
Fowler : Concrete Table Inheritance Represents an inheritance hierarchy of classes with one
Microsoft : Table Per Concrete Type (TPC)
table per concrete class in the hierarchy
TPT Mapping
Fowler : Class Table Inheritance Represents an inheritance hierarchy of classes with one
Microsoft : Table Per Type (TPT)
table for each class
TPH Mapping
Fowler : Single Table Inheritance Represents an inheritance hierarchy of classes as a single table
Microsoft : Table Per Hierarchy (TPH)
that has columns for all the fields of the various classes.
Object Context
Code

ObjectContext
ChangeTracking

Attach
1. Query
Database
Tables
2. Update the Entities
Notifies

3. Save Changes
Querying

• LINQ
– Compiled
– Type Safe Results

• ObjectQuery + Entity SQL


– Entity SQL is a string ... dynamic
– Type Safe Results

• EntityClient Providor + Entity SQL


– API like ADO.NET 2.0
– Not Type safe
– Forward only/Read only
– There is no objectcontext
Entity SQL
• SQL alike Query language
• Can do the same as LINQ (and vice versa)
• Queries on the model, not the database.
• Object Oriented
– dot syntax, TypeOf()
– Is translated to T-SQL by EF (in combination with driver of vendor)
SELECT VALUE il FROM InvoiceLines AS il WHERE il.Invoice.InvoiceCustomerID = 99

• Avoid JOINs
SELECT c.InvoiceDate, c.InvoiceLines FROM ImvoiceModel.Invoice as c
EF4

• POCO support
• Model First Approach
• LazyLoadingEnabled
• Generation of classes by T4 templates
• Foreign Key Support
• Code only
• Stored Procedures – Function Imports
• Complex Types
EF4 : Persisitence Ignorance - POCO
• PI : An object should not know how it is persisted
– Objects should not depend on data access frameworks to
be used
– Test Driven Development, Domain Driven Design
• POCO : plain old CLR object
– Not inheriting from another public class Supplier
{
class public Int32 Id { get; set; }
public string Name { get; set; }
– No attributes public string City { get; set; }
public List<Product> Product { get; set; }
– Serializable }

public class Product


{
public Int32 Id { get; set; }
public string Name { get; set; }
public double Price { get; set; }
public Supplier Supplier { get; set; }
}
EF4 : Model First Approach
EF4 : Lazy Loading option

• By default in EF 3.5 consuming child data of a query


did not query the DB again.
• EF has LazyLoadingEnabled option

ctx.ContextOptions. LazyLoadingEnabled = true;

ctx.ContextOptions. LazyLoadingEnabled = false;

• Default code generation (beta2) : true !


EF4 : Generation of classes by T4 templates

Entity Model in
reads the
EDMX metadata from
the model
executed by
T4 Template
Visual Studio
generates code

Generated Classes
EF4 : Generation of classes by T4 templates
//This generated.
namespace MyDomainClasses
{
<#
foreach(EntityTypeWrapper entity in Edm.SourceEntities.OrderBy(e => e.ModelName))
{
#>
public class My<#=entity.ClassName#>
{
<#
foreach(PrimitiveTypePropertyWrapper property in entity.PrimitiveTypeProperties)
{
#>
public <#=property.PropertyType#> <#=property.Name#> { get; set; }
<#
}
#>
}
<#
}
#>
}
EF4: Self tracking entities in N-tier architecture

• Entity classes (generated in EF 3.5 or EF 4.0 POCO’s)


have no tracking by itself, it’s the objectcontext that
knows what was inserted, updated or deleted.
• The objectcontext is also the only one who knows the
original values of data needed for concurrency
managment
• Distributing an entity outside the instance (think WCF)
of the objectcontext was not easy, you needed to write
your own tracking logic.
• EF4 : supports Self Tracking Entities by selected a T4
template for code generation.

You might also like