ado.net entity framework 4.3 for real web applications

of 25 /25
ADO.NET Entity Framework 4.3 for Real Web Applications Adam Tuliper Software Architect Cegedim DEV215

Author: hoangtuong

Post on 08-Jan-2017

224 views

Category:

Documents


3 download

Embed Size (px)

TRANSCRIPT

ADO.NET Entity Framework 4.3 for Real Web Applications

ADO.NET Entity Framework 4.3 for Real Web ApplicationsAdam TuliperSoftware ArchitectCegedim

DEV215

6/14/2012 2:57 PM 2007 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries.The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

1

About MeAdam TuliperTwitter: @AdamTuliperCompleteDevelopment.blogspot.compluralsight .com authorMSDN Security Topics - December, JanuaryQuestions, Comments, Amazon Gift Cards,Beer, etc [email protected]

3

ORM Effectiveness vs. Current Rice PriceEffectivenessUsing ORMNot using an ORMPrice of rice in China vs Effectiveness2027

Why Entity Framework?FAST Setup Data code written for youNo manual managing ofKeys, Relationships (Order.Customer = customer)Eager/lazy loadingValidationSmart updates only for changed columnsNo changes to object = No update to the databaseAll Major RDMS supportedNo SQL Injection!!Easy API (DbContext), Code First, and Enum support

Whats a Real Web App?Samples inadequate for organized N-Tier appsBeyond prototype or uber-basic CRUDAn app you dont want all code in one projectAn app that clearly has separate layersApps with Complex logic/viewsAn app that could benefit from Dependency Injection (See blog for complete usage with EF)

Everything you needInstall Entity Framework Install-Package EntityFrameworkSQL Compact Toolbox, EF Power ToolsCreate your projects in layersWeb Domain Entities and Repository InterfacesDataAccess (Contains repository implementation and Context)Test ProjectDesign/Create EntitiesAdd ValidationHandle concurrencyUse Repository Pattern for ALL CRUD operations

6

Model First/Database FirstProsVisual Designer -> Architectural documentationEasy code regeneration with model or db changesVery fast implementationConsMay not prefer to deal with XML based EDMX fileSome may feel loss of control without pure codePlease use: ADO.NET DbContext Generator T4 Templates

7

Code FirstProsPOCO by default simple!Can specify initializers to create databaseFluent API or clean attributes for validationConsNo Visual DesignerNo direct stored procedure support for operations. Easily can call Context.Database.SqlQuery(..) in repository though

Requires only model(s) and a context class. Can reverse engineer an existing database

8

Understanding EFThree important itemsContextThe spork of Connection, Command, TransactionHandles all CRUD to databaseParties after midnight cause honey badger dont carePOCOEntity StatesQuery easily via: context.Entry(customer).StateAdded, Detached, Unchanged, Modified

TechEd 20126/14/2012 2:57 PM 2012 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries.The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

9

Basic Architecture

10

Background - POCOsIsnt it just a DTO?100% Persistent Ignorant

POCODTOCan contain business logicXShould not reference framework implementations (ex. EF libraries)XXDesigned to transfer between layersXKnows nothing of persistenceXXTransfers StateX

11

Real Web ConsiderationsUse the Repository Pattern!Swappable (think Azure)Single point of change (to/from stored proc)Convert all collections to IEnumerable firstAvoid deferred execution outside of context scope: var customer = ctx.Customers;var customer = ctx.Customers.ToList();New context per each request - Do not cache.Use Universal Membership providerSupports SQL Server, SQLCE, SQL Express, SQL Azure

12

MVC ConsiderationsFor Views, dont use EF entities, map to ViewModelsAutomapper is your friend http://automapper.org/ViewModel + AutoMapper maps entities for GET onlyDbContext is not thread safe. Instantiate a new one per request in constructor or via DIDo not cache it or use a static instance.Dispose Context when done (DI helps)Do not throw all EF code into controllerMVC Controller and code behinds should be THIN & Organized!Greatly helps testing

13

Web Forms ConsiderationsCan magically use EntityDataSource/ObjectDataSourceI recommend handling context lifetime yourselfData binding must occur in the context scope unless ToArray/ToList()Do not add entities to ViewStateASP.NET 4.5 now has strongly typed controlsCan easily use ViewModels and AutoMapper

14

ValidationsAll work in MVC or Web Forms for server side validationFluent API (Integrated in MVC4, not in MVC3)Data AnnotationsIValidateableObjectAll triggered by context.SaveChanges()EF throws DbEntityValidationExceptionClient side validation?Must use data annotations for MVCWeb Forms 4.5 supports data annotationsOtherwise no tight integration

15

Handling ConcurrencyAutomatic via [TimeStamp] attribute & rowversion typeMust catch DbUpdateConcurrencyExceptionIn both MVC & Web FormsMVC -manually include models hidden timestamp fieldHtml.HiddenFor(o=>o.TimeStamp)Web Forms various methodsStore timestamp as hidden field on formGridView: DataKeyNames="CustomerId,Timestamp"

16

Automatic Data MigrationsProvides mechanism to migrate model changes to DBMigrations are handled from the package managerEnable-Migrations -EnableAutomaticMigrations Update-Database Can downgrade to a past migration and remove columns

17

Thanks!!http://completedevelopment.blogspot.com/2012/06/dependency-injection-with-entity.htmlcompletedevelopment.blogspot.com/2012/06/unit-of-work-pattern-with-entity.htmlwww.asp.net/web-forms/tutorials/aspnet-45/getting-started-with-aspnet-45-web-forms/create_the_data_access_layerCompleteDevelopment.blogspot.comTwitter: @AdamTuliperQuestions, Comments, Gift Cards, Beer [email protected]

Related Content

DEV 301 ASP.NET Roadmap: One ASP.NET Web Forms, MVC, and Web APITLC - Developer Tools, Languages & Frameworks Ask an expert!70-516 Accessing Data with Microsoft .NET Framework 4

DEV333 The Scaling Habits of Microsoft ASP.NET Applications

19

DEV Track Resources

Visual Studio Home Page :: http://www.microsoft.com/visualstudio/en-usJason Zanders Blog :: http://blogs.msdn.com/b/jasonz/Facebook :: http://www.facebook.com/visualstudio

Twitter :: http://twitter.com/#!/visualstudio

Somasegars Blog :: http://blogs.msdn.com/b/somasegar/

20

Resources

Connect. Share. Discuss.http://northamerica.msteched.com

Learning

Microsoft Certification & Training Resourceswww.microsoft.com/learning

TechNet

Resources for IT Professionalshttp://microsoft.com/technet

Resources for Developershttp://microsoft.com/msdn

21

Required Slide

Complete an evaluation on CommNet and enter to win!

22

MS Tag

Scan the Tagto evaluate thissession now onmyTechEd Mobile

23

2012 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries.The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

6/14/2012 2:58 PM 2009 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries.The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

24

6/14/2012 2:57 PM 2009 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries.The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

25