1
Goals of Entity Framework
2
The “Impedance Mismatch”
Source: Gil Fink http://blogs.microsoft.co.il/blogs/gilf 3
Make a persistency layer that maps from SQL to OOP
It is a better solution than accessing the db from many places in the application
But it still can raise some problems, e.g.:
Tight coupling between application and db
(e.g. can not change tables in the db without making changes to domain classes in the application)
Hard to maintain (e.g. SQL queries, dependent classes etc. might be spread in many places)
Application and db domains are probably not the same
Etc.
4
ORM is:
• (Wikipedia) A programming technique for converting data between incompatible type systems (such as DBMS) in relational databases and object-oriented programming languages.
• It does the plumbing work for you to aggregate, modify and save your data back to its storage in Object Oriented manner (easy to understand, maintain and extend)
Source: Bishoy Demian
5
NHibernate, open source
.netTiers, open source, based on commercial code generation tool (Codesmith)
Developer Express, eXpress Persistent Objects (XPO)
LLBLGen, open source drivers, commercial
TierDeveloper, free ORM and code generation tool
Subsonic, open source
Source: Bishoy Demian
6
Data access framework
Supports data-centric applications and services
Enables programming against a conceptual application model
Enables independency of any data storage engine or relational schema
Source: Gil Fink http://blogs.microsoft.co.il/blogs/gilf 7
EF uses a model called an E ntity D ata M odel (EDM)
EDM is a client-side data model
EDM is an abstraction layer on top of the data storage
Remove the pain of
Interacting with the data storage
Translating the data into objects
Source: Gil Fink http://blogs.microsoft.co.il/blogs/gilf 8
Goal: Simple and seamless data access for the .NET platform
Better layering
Better re-use of existing knowledge and assets
EDM – Entity Data Model
An abstract model for defining entities and relationships
Includes schema and mapping
Store Schema Definition (SSDL)
Conceptual Schema Definition (CSDL)
Mapping Schema between the two (MSL)
Entity Framework
An implementation of EDM and an ORM layer on top
A framework for using entities over data
Source: Jeff Derstadt 9
The Entity Framework has no knowledge of the database that stores the data
It connects and interacts with the database through a provider that is usually declared in the configuration file
As in ADO.NET the providers are supplied by the dbms vendors
Some supported dbms ’es:
SQLServer ;-)
Oracle
MySQL postgreSQL db2
...
Source: Jeff Derstadt 10
(VS 2008 and .NET 3.5 SP1)
DB Model
Design time
(VS 2010 and .NET 4.0)
Design time
DB Model
Design time Design time
(Entity Framework Feature CTP3)
DB Model
Runtime Runtime
Code why? it already exists, or you want low level control over the database
Code why? you want separation from code and database in a declarative format
Code why? primarily focused on code shape, database is an implementation detail
Source: Jeff Derstadt 11
Model-first development
Automatic pluralization
Lazy loading
POCO class support
T4 Code Generation
Template customization
ObjectSet/IObjectSet
Foreign keys in models
Virtual SaveChanges
ExecuteStoreQuery
ExecuteStoreCommand
More LINQ operator support
Source: Jeff Derstadt
There’s more!
Self-tracking entities
SQL generation improvements
ObjectStateManager control
WPF designer integration
SPROC import improvements
Model defined functions
Code-Only development
(Feature CTP)
12
How to create an entity model from an existing database
13
Create a class library project
Add new item, select the ADO.NET Entity Data Model template
14
When database first, select ”Generate From Database”
Select the database connection
Select the database entities that shall be visible
Important: enable Pluralize... and foreign keys
15
Adjust the entities, mapping etc.
16
Graphical representation of an EDM and its members
Enables adding more features to the model
Enables properties configuration
Enables updating from the data store
Enables model validation
Source: Gil Fink http://blogs.microsoft.co.il/blogs/gilf 17
Singularization and pluralization:
The ‘many’ part is named in plural, e.g. Orders
The ‘one’ part is named in single, e.g. Customer
Navigation Properties:
Make it possible to navigate from one entity (in code an object) to another.
18
The Entity Data Model (EDM) is a schema language for entities.
It allows for the definition of entities, relationships between entities and logical sets of related entities
Storage Metadata Schema (SSDL) is a formal description of the database that persists data for an application built on the
Entity Data Model (EDM).
The entities and associations declared in this schema are the basis for mapping entities and associations in the conceptual schema to the corresponding entities in the storage model.
Mapping Specification (MSL) is used to connect the types declared in conceptual schema definition language (CSDL) to database metadata that persists data.
Conceptual Schema (CSDL) is a design template for the object model that will be used by applications built on the Entity Data
Model (EDM).
19
The output of the designer is an XML document that consists of 3 parts:
Source: Julia Lerman
20
Entity classes are automatically generated from the EDM
The classes consists primary of properties and events
So it is possible to get and set values, and to get notified when an event occurs, e.g. an update
21
You should place the EDM and therefore the generated code in a class library (dll-assembly).
Then you can access the EDM from your data-tier, business-tier, persistent-tier, etc.
When you access from another assembly remember to add a reference to your EDM assembly and to system.data.entity
And add ‘using’ for your EDM in the code where the context class is used
The connection string in the app.config must also be in the app-config for the exe-assembly.
But it is easier to see in a demo
22
Access it from a console application
Do a simple LINQ query and write the result on screen
23
• Queries are built against a data model
• EDM query transform into data storage query
• Query results materialize into model entities
Source: Gil Fink http://blogs.microsoft.co.il/blogs/gilf
The image is taken from
Julia Lerman ’s book
Programming
Entity
Framework,
1st Edition
You can query the model in different ways:
Using LINQ
Using Entity SQL
With Object Services
With Entity Client
25
Straight forward LINQ syntax
IntelliSense support var context = new NWEntities (); var query = from c in context.Customers
where c.Orders.Count()>25 select c; foreach ( Customer c in query)
Console .WriteLine(c.CompanyName);
26
T-SQL-like query language
EF translates Entity SQL into storage-specific queries
Lazy queries
No IntelliSense support
String queryString = @"SELECT VALUE c
FROM Customers AS c
WHERE c.Country='UK'" ; var customers = Context.CreateQuery< Customer >(queryString); foreach ( Customer c in customers)
Console .WriteLine(c.CompanyName);
27
Works like traditional PODA: Get a set of records from the data store
E.g. like SQLClient or OracleClient
No IntelliSense support using ( var conn = new EntityConnection ( "name=NWEntities" )) { conn.Open(); var qStr = @"SELECT VALUE c
FROM Customers AS c
WHERE c.Country='UK'" ; var cmd = conn.CreateCommand(); cmd.CommandText = qStr; using ( var rdr = cmd.ExecuteReader()){ while (rdr.Read()){
Console .WriteLine(rdr.GetString(1));
}
}
}
28
Changes to entities are stored in memory:
Every entity in ObjectContext has a ObjectStateEntry
ObjectContext uses ObjectStateEntries to track entity changes
The context.SaveChanges() method is used to update the database according to ObjectStateEntries
Rollback (in memory) can be done with context.SaveChanges(false)
The normal mutations insert, update and delete are possible
29
Create a new instance (entity) of the class.
Evt. set references to related objects (as normal in oop)
Add the entity to the context.
Console .WriteLine( "Create new order" ); var order = new Order { CustomerID = "SEVES" , EmployeeID = 1 }; context.AddToOrders(order); context.SaveChanges();
30
Just get a reference to the entity
Make the changes
And call context.SaveChange()
Console .WriteLine( "Changing order" ); var order = from o in context.Orders
where o.OrderID == 11078 select o; order.Single().OrderDate = DateTime .Now; context.SaveChanges();
31
Get a reference to the entity
Call context.DeleteObject(theEntity)
Call context.SaveChanges()
Console .WriteLine( "Deleting order" ); var order = from o in context.Orders
where o.OrderID == 11078 select o; context.DeleteObject(order.Single()); context.SaveChanges();
32
To types of inheriance
Table-per-Hierarchy Inheritance
Table-per-Type Inheritance
These covers two different situations in SQL databases without O/R
In the first situation you ’ll have one ”type table” where different subtypes are listed.
In the second situation you ’ll have a specialized table pr. type
33
Example based on School database from msdn
Source: http://mosesofegypt.net/post/Inheritance-and-
Associations-with-Entity-Framework-Part-1.aspx
34
Example based on School database from msdn
Source: http://mosesofegypt.net/post/Inheritance-and-
Associations-with-Entity-Framework-Part-2.aspx
35
Fields that are not used so frequently might be extracted to another entity with a 1-1 relation
36
//Get photo when needed
AssoEntities assoContext = new AssoEntities (); var employee = ( from e in assoContext.Employees
select e).FirstOrDefault();
Console .WriteLine(employee.LastName);
Console .WriteLine( employee.EmployeePhoto.Photo.Length.ToString());
//Get the photo together with the rest of Employee
AssoEntities assoContext = new AssoEntities (); var employee = ( from e in assoContext.Employees.Include( "EmployeePhoto" ) select e).FirstOrDefault();
Console .WriteLine(employee.LastName);
Console .WriteLine( employee.EmployeePhoto.Photo.Length.ToString());
37