You are on page 1of 39

ENTITY FRAMEWORK V2

BEST PRACTICES
Microsoft Innovation Day 2010, May 11, 2010

Andri Yadi | a@dycode.com


CEO, DyCode | MVP, VSTO
http://itunes.com/apps/movreak
JSON

HTTP/REST WCF Data Services

Entity Framework

Real-world Scenario SQL Server 2008


Dr. EF. Codd
INSERT
UPDATE

SELECT
DELETE

WHERE
HAVING
ORDER BY

Then we code in SQL


RIGHT
JOIN

COUNT
UNION MIN/MAX
LEFT
ADO.NET code

SqlCommand oCmd;
SqlDataReader oDR;

string connString = ConfigurationManager.


ConnectionStrings["OracleConnString"].
ConnectionString;
SqlConnection conn = new SqlConnection(connString);

string selectQuery;
int _returnValue = 0;

selectQuery = “SELECT COUNT(OrderID) from Orders“ +


“where EmployeeID=@EmpID”;

conn.Open();
oCmd = new SqlCommand(selectQuery, conn);
oCmd.Parameters.Add(“@EmpID”, SqlDbType.Int);
oCmd.Parameters[“@EmpID”].Value = employeeID;
oDR = oCmd.ExecuteReader();
if (oDR.Read())
_returnValue = oDR.GetInt32(0);

oDR.Close();
conn.Close();
The Dilemma

Developers like to work


re Databases are designed for
wa &
with oft cts
S ite
• Maintainability Data
• Conceptual Models
rc h opers • Security Des base
A vel
• Business Objects • Efficiency Adm igners &
De inist
• Scalability rato
s r
RDO DAO ADO ADO.NET
(1992) (1996)
Enough! We need ORM!
• Technique for working with
relational tables as if they were
Object
objects in memory
Relational
• Hide away the complexity of the
Mapping underlying tables and give a
uniform way of working with data
• Development productivity
Why ORM? • Database independence
• Database portability
• Typed Datasets
• Objectspaces ‘v1’
• Objectspaces ‘v2’
• Microsoft Business
Many attempts Framework
• WinFS
• Linq to SQL  Will “RIP”
• NHibernate  Not Microsoft’s
• Microsoft’s strategic technology
ADO.NET Entity • Used in other Microsoft
Framework technologies (reporting services)
• V2 released with .NET 4.0

14
Entity Data • Invented in the 1970s, by Dr.
Model Peter Chen
• ERM
• Conceptual Layer
• Mapping Layer
• Storage Layer

• Now: EDM in ADO.NET


Entity Framework
Entity Framework vs LinqToSQL

Entity
LinqToSQL
Framework
Specific to Microsoft SQL Server Storage Provider Independent

Supports many types of Object Relational


Maps 1-to-1 to database tables, views, stored
Mappings, including many-to-many
procedures and functions
relationships

Ideal for building conceptual models that


Ideal for quick data access construction to
aggregate a variety of tables, sources, service
relatively well designed SQL Server databases
etc. into a mash-up domain model

Supports also Table per Subclass, Entity


Supports Table per Hierarchy Inheritance
Splitting, Horizontal Splitting, and more…
LET’S GO DEEPER ON EF2
Entity
LINQ to
SQL
Entities
Query
IEnumerable
<T>

Entity Framework
EDM
Entity Command
Conceptual SQL
Tree
Query
Model EntityDataReader

Mapping Entity Framework

Command
Storage Tree
EntityDataReader
Model

Entity Framework
Model-first
DEMO
• Structure the initial query in such
a way that all of the required
objects are returned in the initial
Eager Loading query
• from c in
nw.Customers.Include("Orders")
select c;
• Explicitly request to load the
Explicit Loading related objects
• customer.Orders.Load();
• Related objects are loaded
Lazy Loading automatically for you when you
access them
• Plain Old CLR Object
• User your own POCO objects
with no EF attributes
POCO Support • Code your POCO classes
• Code Entity Framework Context
• Or use T4 POCO entity generator
by VS2010
• Do I still need an EDM? Yes
• How is metadata mapped to
POCO entities? Convention
Questions on based mapping
• Entity Type, Property, and Complex
POCO Types names must match those
defined by in EDM
• Is deferred/lazy loading
supported? Yes
• Declare lazy-loaded property as
virtual
Lazy Loading on
• Make sure to enable
POCO ContextOptions.LazyLoadingEnabled
• What’s under the hood?
POCO Change • Snapshot-based
tracking • Proxy-based
POCO
DEMO
Generate EDM from database
DEMO
• Connections to database vs.
amount of data
• You can work with stored
procedures
• You can work with views
Performance &
security? • You can define how the
ADO.NET Entity Framework
loads your data to
• Eager
• Lazy
• (Explicit)
EF V2 IN DISTRIBUTED SYSTEM
Data Binding

Proxy A WCF Service

Entity Framework

ObjectContext not available ObjectContext available

Distributed system – WCF service SQL Server 2008


JSON/
XML

DataServiceContext
Data Binding

HTTP/REST
WCF Data Service
HTTP/REST

Entity Framework

ObjectContext not available ObjectContext available

Distributed system – WCF Data service SQL Server 2008


SO, WHAT’S NEW IN EF2?
• Foreign-keys supported in
the conceptual model
• Testability enhancements
• IObjectSet<T> and
ObjectSet<T>
Entity
• Easier to mock data context
enhancements and data entities for tests
• Lazy loading for related
objects
• Options now for explicit or
implicit loading
• Persistence ignorant objects
• POCO objects with no EF attributes, etc.
• Mapped to conceptual model via
convention
• Change tracking possible with generated

Support for proxies or snapshot


• Managing types in n-tier applications
persistence • Easier to add/attach objects to a context
ignorant objects • More control over object state
• Issues you should consider
• You still need the Entity Data Model
(edmx)
• To use objects with WCF – use
ProxyDataContractResolver
• Support for complex types

• Singularization & pluralization


• Model first development
Designer • Creates DDL for database based on
your model
enhancements
• Designer extensibility
• Influence the EDMX generation
• Add visuals
• Influence DDL creation
• Based on T4 templates
• Included as of VS 2008
• Runtime support, but not
much design support
• T4 and Entity Framework
Code generation • T4 used to generate code
customization from model
• Create new T4 templates to
use instead
• Add validation logic
• Create POCO objects
• ADO.NET team blog – keep up with
new features in Entity framework
• http://blogs.msdn.com/adonet

References • ADO.NET C# POCO Entity Generator


• ADO.NET C# Web Site POCO Entity Ge
nerator 
• WCF Data Services team blog
• http://blogs.msdn.com/astoriateam
DyCode
www.dycode.com | office@dycode.com
Dynamic IT Solutions for Optimal Business Value

You might also like