entity framework v2 best practices
DESCRIPTION
Entity Framework v2 in .NET 4.0. Some intro and best Practices.TRANSCRIPT
ENTITY FRAMEWORK V2BEST PRACTICES
Microsoft Innovation Day 2010, May 11, 2010
Andri Yadi | [email protected]
CEO, DyCode | MVP, VSTO
http://itunes.com/apps/movreak
Entity Framework
SQL Server 2008
WCF Data ServicesHTTP/REST
JSON
Real-world Scenario
Dr. EF. Codd
DELETESELECT
COUNT
LEFTUNION MIN/MAX
JOIN
HAVINGORDER BY
RIGHT
INSERT
WHERE
UPDATE
Then we code in SQL
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();
ADO.NET code
Developers like to work with• Conceptual
Models• Business
Objects
Databases are designed for• Maintainability• Security• Efficiency• Scalability
The Dilemma
Software
Archite
cts
&
Developers
Database Designers & Administrators
ADO.NET
ADO(1996)
DAO(1992)
RDO
Enough! We need ORM!
Object Relational Mapping
• Technique for working with relational tables as if they were objects in memory
• Hide away the complexity of the underlying tables and give a uniform way of working with data
Why ORM?
• Development productivity
• Database independence• Database portability
Many attempts
• Typed Datasets• Objectspaces ‘v1’• Objectspaces ‘v2’• Microsoft Business
Framework• WinFS• Linq to SQL• NHibernate
Will “RIP” Not Microsoft’s
ADO.NET Entity Framework
• Microsoft’s strategic technology
• Used in other Microsoft technologies (reporting services)
• V2 released with .NET 4.0
14
Entity Data Model
• Invented in the 1970s, by Dr. Peter Chen
• ERM• Conceptual Layer
• Mapping Layer
• Storage Layer
• Now: EDM in ADO.NET Entity Framework
LinqToSQL
Specific to Microsoft SQL Server
Maps 1-to-1 to database tables, views, stored procedures and functions
Ideal for quick data access construction to relatively well designed SQL Server
databases
Supports Table per Hierarchy Inheritance
Entity Framework
Storage Provider Independent
Supports many types of Object Relational Mappings, including many-to-
many relationships
Ideal for building conceptual models that aggregate a variety of tables,
sources, service etc. into a mash-up domain model
Supports also Table per Subclass, Entity Splitting, Horizontal Splitting, and
more…
Entity Framework vs LinqToSQL
LET’S GO DEEPER ON EF2
EDMEntity Framework
Conceptual Model
Entity Framework
IEnumerable<T>
EntityDataReader
LINQ to Entities
Entity SQL
Query
Command Tree
Entity SQL
Query
Entity Framework
EntityDataReader
Command TreeStorage
Model
Mapping
DEMOModel-first
Eager Loading
• Structure the initial query in such a way that all of the required objects are returned in the initial query
• from c in nw.Customers.Include("Orders") select c;
Explicit Loading
• Explicitly request to load the related objects
• customer.Orders.Load();
Lazy Loading• Related objects are loaded
automatically for you when you access them
POCO Support
• Plain Old CLR Object• User your own POCO
objects with no EF attributes• Code your POCO classes• Code Entity Framework
Context
• Or use T4 POCO entity generator by VS2010
Questions on POCO
• Do I still need an EDM? Yes• How is metadata mapped
to POCO entities? Convention based mapping• Entity Type, Property, and
Complex Types names must match those defined by in EDM
• Is deferred/lazy loading supported? Yes
Lazy Loading on POCO
• Declare lazy-loaded property as virtual
• Make sure to enable ContextOptions.LazyLoadingEnabled
• What’s under the hood?
POCO Change tracking
• Snapshot-based• Proxy-based
DEMOPOCO
DEMOGenerate EDM from database
Performance & security?
• Connections to database vs. amount of data
• You can work with stored procedures
• You can work with views• You can define how the
ADO.NET Entity Framework loads your data to • Eager • Lazy• (Explicit)
EF V2 IN DISTRIBUTED SYSTEM
Entity Framework
SQL Server 2008
A WCF Service
Distributed system – WCF service
Pro
xy
Data
B
indin
g
ObjectContext available
ObjectContext not available
Entity Framework
SQL Server 2008
WCF Data Service
HTTP/REST
Distributed system – WCF Data service
HTTP/REST
Data
Serv
iceC
ont
ext
Data
B
indin
g
ObjectContext available
ObjectContext not available
JSON/XML
SO, WHAT’S NEW IN EF2?
Entity enhancements
• Foreign-keys supported in the conceptual model
• Testability enhancements• IObjectSet<T> and
ObjectSet<T>• Easier to mock data
context and data entities for tests
• Lazy loading for related objects• Options now for explicit
or implicit loading
Support for persistence ignorant objects
• Persistence ignorant objects• POCO objects with no EF
attributes, etc.• Mapped to conceptual model via
convention• Change tracking possible with
generated proxies or snapshot
• Managing types in n-tier applications• Easier to add/attach objects to a
context• More control over object state
• Issues you should consider• You still need the Entity Data
Model (edmx)• To use objects with WCF – use
ProxyDataContractResolver
Designer enhancements
• Support for complex types
• Singularization &
pluralization• Model first development
• Creates DDL for database based on your model
• Designer extensibility • Influence the EDMX
generation• Add visuals• Influence DDL creation
Code generation customization
• Based on T4 templates• Included as of VS 2008• Runtime support, but not
much design support
• T4 and Entity Framework • T4 used to generate code
from model• Create new T4 templates
to use instead
• Add validation logic• Create POCO objects
References
• ADO.NET team blog – keep up with new features in Entity framework• http://blogs.msdn.com/adonet
• ADO.NET C# POCO Entity Generator
• ADO.NET C# Web Site POCO Entity Generator
• WCF Data Services team blog• http://blogs.msdn.com/astoriateam
DyCodewww.dycode.com | [email protected]
Dynamic IT Solutions for Optimal Business Value