22
Jeff Derstadt Senior Development Lead Microsoft Corporation [email protected] Entity Framework Deep Dive Patterns & Architecture

Jeff Derstadt Senior Development Lead Microsoft Corporation [email protected] Patterns & Architecture

Embed Size (px)

Citation preview

Page 1: Jeff Derstadt Senior Development Lead Microsoft Corporation jeffders@microsoft.com Patterns & Architecture

Jeff DerstadtSenior Development LeadMicrosoft [email protected]

Entity Framework Deep Dive

Patterns & Architecture

Page 2: Jeff Derstadt Senior Development Lead Microsoft Corporation jeffders@microsoft.com Patterns & Architecture

AgendaRepository pattern in MVCBetter testabilityBuilding N-tier ApplicationUsing Stored ProceduresCode First Programming

Page 3: Jeff Derstadt Senior Development Lead Microsoft Corporation jeffders@microsoft.com Patterns & Architecture

Mult

i Ti

er

Sin

gle

Tie

r

Separation of concernsCentralize and encapsulate data access codeIsolate upper layers from data access infrastructureProvide greater control over data access

Repository Pattern Goals & Benefits

User Interface

Data Access Layer

Database

Web Silverlight

New Data Access LayerData Access Layer

Fake Database

Business Logic / Controller

Page 4: Jeff Derstadt Senior Development Lead Microsoft Corporation jeffders@microsoft.com Patterns & Architecture

Repository is a class with data access methodsEncapsulates query and update operationsExposes entity classes with persistence ignorance

Often used with the UnitOfWork patternEncapsulates transaction and save operations

Repository Pattern Overview

public class BlogRepository{ public BlogRepository(IUnitOfWork unitOfWork) { ... }

public IEnumerable<Blog> GetAllBlogs() { ... }

public void AddPost(Post post) { ... }}

Page 5: Jeff Derstadt Senior Development Lead Microsoft Corporation jeffders@microsoft.com Patterns & Architecture

Best PracticesWrap the ObjectContextCreate separate repositories for each aggregate rootMultiple repositories can share same ObjectContext as a unit of workQuery methods return IEnumerable<T>Repository interface is a strong contract

Common AlternativesQuery methods return IQueryable<T>Repository<T> base class

Repository using Entity Framework

Page 6: Jeff Derstadt Senior Development Lead Microsoft Corporation jeffders@microsoft.com Patterns & Architecture

Repository using Entity Framework

Demo

Page 7: Jeff Derstadt Senior Development Lead Microsoft Corporation jeffders@microsoft.com Patterns & Architecture

Goal: swap out the data access code with something in-memory

It’s fasterYou have more control

Two approachesFake your derived ObjectContext

Build an interface BlogContext IBlogContextUse IObjectSet

It’s IQueryableIt’s updateable (AddObject, DeleteObject, etc.)It’s testable because you can implement your own

Fake your Repository

Entity Framework Testability

Page 8: Jeff Derstadt Senior Development Lead Microsoft Corporation jeffders@microsoft.com Patterns & Architecture

Entity Framework Testability

Demo

Page 9: Jeff Derstadt Senior Development Lead Microsoft Corporation jeffders@microsoft.com Patterns & Architecture

N-Tier Options

Low HighComplexity

DataSetData

Transfer Objects

High

Interoperabilit

y

??Self-Tracking

Entities

Page 10: Jeff Derstadt Senior Development Lead Microsoft Corporation jeffders@microsoft.com Patterns & Architecture

T4 Templates – can create a template that generates default DTOs for each entityForeign Keys –Manage relationships using scalar valuesAbility to set current and original values

For the whole entityApplyCurrentValuesApplyOriginalValues

For member values

ChangeObjectState – change the state of an entityChangeRelationshipState – change the state of a relationship

Data Transfer Objects in EF 4.0

Page 11: Jeff Derstadt Senior Development Lead Microsoft Corporation jeffders@microsoft.com Patterns & Architecture

EF 4.0 introduces self-tracking entitiesIt’s easy to:

Get started: Add the entity template to your projectMake changes: Just work with your objectsPersist changes: Call one method, ApplyChanges

Entities have no dependencies on EFEntities track their own changes as they happenWire-format enables services to be used on other platforms like Silverlight and Java

Achieving Low Complexity

Page 12: Jeff Derstadt Senior Development Lead Microsoft Corporation jeffders@microsoft.com Patterns & Architecture

Self Tracking Entities

Demo

Page 13: Jeff Derstadt Senior Development Lead Microsoft Corporation jeffders@microsoft.com Patterns & Architecture

You are communicating across tiersYou want to persist your change-setYou need more control over your entities on the client and/or the serverYou need more control over your service implementation

When to use self-tracking entities

Page 14: Jeff Derstadt Senior Development Lead Microsoft Corporation jeffders@microsoft.com Patterns & Architecture

Now available in the designerCan map one or more of

SelectInsertUpdateDelete

Still not there, but planned in the next releaseMultiple result setsTVFs

Stored Procedures

Page 15: Jeff Derstadt Senior Development Lead Microsoft Corporation jeffders@microsoft.com Patterns & Architecture

Stored Procedures

Demo

Page 16: Jeff Derstadt Senior Development Lead Microsoft Corporation jeffders@microsoft.com Patterns & Architecture

WhenDatabase is an implementation detailModels are overheadJust let me code!

Code First is where you startAvailable as a CTP for VS 2010 and .NET 4.0http://www.microsoft.com/downloads/

Code First

Page 17: Jeff Derstadt Senior Development Lead Microsoft Corporation jeffders@microsoft.com Patterns & Architecture

Code First

Demo

Page 18: Jeff Derstadt Senior Development Lead Microsoft Corporation jeffders@microsoft.com Patterns & Architecture

Code First is a work in progressAvailable post .NET 4.0Planned additions

Conventions, conventions, conventionsPrimary keys and store generated patternsRelationship inversesForeign key constraintsReachabilityComplex types

Data annotation attribute support (existing and new)Improved APIBetter integration (OData, WCF RIA Services, ASP.NET, etc.)

Code First

Page 19: Jeff Derstadt Senior Development Lead Microsoft Corporation jeffders@microsoft.com Patterns & Architecture

New features for SQL ServerEnum supportCustom types (UDTs) such as spatialTVFsAlternate keys

New features for performance and scalabilityLarger model supportIncremental model loadingScalable design surface

New features for productivityEnhanced API for Code FirstMore control over entity shape (type transformations, fields, factory methods)More control over change tracking and validationBuilt-in logging and tracing

The Road Ahead

Page 20: Jeff Derstadt Senior Development Lead Microsoft Corporation jeffders@microsoft.com Patterns & Architecture

Use the Repository pattern and wrap the ObjectContext to achieve better seperation of concernsBuild better unit tests by faking your ObjectContext and ObjectSetsUse self-tracking entities as a low complexity, higher interoperable N-tier solutionImproved stored procedure support in EF4CodeFirst is coming and allows you to build models with code

In Summary

Page 21: Jeff Derstadt Senior Development Lead Microsoft Corporation jeffders@microsoft.com Patterns & Architecture

Thank you for your Attention!For more Information please contact

Jeff DerstadtSenior Development Lead

[email protected]

Microsoft Corporation1 Microsoft WayRedmond, WA 98052 USA

http://msdn.microsoft.com/data

Gives us feedbackhttp://blogs.msdn.com/adonethttp://blogs.msdn.com/efdesign

Page 22: Jeff Derstadt Senior Development Lead Microsoft Corporation jeffders@microsoft.com Patterns & Architecture