entity framework v2 best practices

39
ENTITY FRAMEWORK V2 BEST PRACTICES Microsoft Innovation Day 2010, May 11, 2010 Andri Yadi | [email protected] CEO, DyCode | MVP, VSTO

Upload: andri-yadi

Post on 12-Jan-2015

9.732 views

Category:

Technology


5 download

DESCRIPTION

Entity Framework v2 in .NET 4.0. Some intro and best Practices.

TRANSCRIPT

Page 1: Entity Framework v2 Best Practices

ENTITY FRAMEWORK V2BEST PRACTICES

Microsoft Innovation Day 2010, May 11, 2010

Andri Yadi | [email protected]

CEO, DyCode | MVP, VSTO

Page 2: Entity Framework v2 Best Practices

http://itunes.com/apps/movreak

Page 3: Entity Framework v2 Best Practices

Entity Framework

SQL Server 2008

WCF Data ServicesHTTP/REST

JSON

Real-world Scenario

Page 4: Entity Framework v2 Best Practices

Dr. EF. Codd

Page 5: Entity Framework v2 Best Practices
Page 6: Entity Framework v2 Best Practices

DELETESELECT

COUNT

LEFTUNION MIN/MAX

JOIN

HAVINGORDER BY

RIGHT

INSERT

WHERE

UPDATE

Then we code in SQL

Page 7: Entity Framework v2 Best Practices

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

Page 8: Entity Framework v2 Best Practices

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

Page 9: Entity Framework v2 Best Practices

ADO.NET

ADO(1996)

DAO(1992)

RDO

Page 10: Entity Framework v2 Best Practices

Enough! We need ORM!

Page 11: Entity Framework v2 Best Practices

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

Page 12: Entity Framework v2 Best Practices

Why ORM?

• Development productivity

• Database independence• Database portability

Page 13: Entity Framework v2 Best Practices

Many attempts

• Typed Datasets• Objectspaces ‘v1’• Objectspaces ‘v2’• Microsoft Business

Framework• WinFS• Linq to SQL• NHibernate

Will “RIP” Not Microsoft’s

Page 14: Entity Framework v2 Best Practices

ADO.NET Entity Framework

• Microsoft’s strategic technology

• Used in other Microsoft technologies (reporting services)

• V2 released with .NET 4.0

14

Page 15: Entity Framework v2 Best Practices

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

Page 16: Entity Framework v2 Best Practices

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

Page 17: Entity Framework v2 Best Practices

LET’S GO DEEPER ON EF2

Page 18: Entity Framework v2 Best Practices

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

Page 19: Entity Framework v2 Best Practices

DEMOModel-first

Page 20: Entity Framework v2 Best Practices

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;

Page 21: Entity Framework v2 Best Practices

Explicit Loading

• Explicitly request to load the related objects

• customer.Orders.Load();

Page 22: Entity Framework v2 Best Practices

Lazy Loading• Related objects are loaded

automatically for you when you access them

Page 23: Entity Framework v2 Best Practices

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

Page 24: Entity Framework v2 Best Practices

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

Page 25: Entity Framework v2 Best Practices

Lazy Loading on POCO

• Declare lazy-loaded property as virtual

• Make sure to enable ContextOptions.LazyLoadingEnabled

• What’s under the hood?

Page 26: Entity Framework v2 Best Practices

POCO Change tracking

• Snapshot-based• Proxy-based

Page 27: Entity Framework v2 Best Practices

DEMOPOCO

Page 28: Entity Framework v2 Best Practices

DEMOGenerate EDM from database

Page 29: Entity Framework v2 Best Practices

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)

Page 30: Entity Framework v2 Best Practices

EF V2 IN DISTRIBUTED SYSTEM

Page 31: Entity Framework v2 Best Practices

Entity Framework

SQL Server 2008

A WCF Service

Distributed system – WCF service

Pro

xy

Data

B

indin

g

ObjectContext available

ObjectContext not available

Page 32: Entity Framework v2 Best Practices

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

Page 33: Entity Framework v2 Best Practices

SO, WHAT’S NEW IN EF2?

Page 34: Entity Framework v2 Best Practices

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

Page 35: Entity Framework v2 Best Practices

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

Page 36: Entity Framework v2 Best Practices

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

Page 37: Entity Framework v2 Best Practices

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

Page 38: Entity Framework v2 Best Practices

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

Page 39: Entity Framework v2 Best Practices

DyCodewww.dycode.com | [email protected]

Dynamic IT Solutions for Optimal Business Value