SlideShare a Scribd company logo
1 of 39
Entity framework v2Best Practices Microsoft Innovation Day 2010, May 11, 2010 AndriYadi| a@dycode.com CEO, DyCode | MVP, VSTO
http://itunes.com/apps/movreak
JSON WCF Data Services HTTP/REST 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 SqlCommandoCmd; SqlDataReaderoDR; string connString = ConfigurationManager. ConnectionStrings["OracleConnString"]. ConnectionString; SqlConnectionconn = 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 Software Architects & 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
Entity Framework vsLinqToSQL
Let’s go deeper on EF2
IEnumerable<T> LINQ to Entities Entity SQL Query Entity Framework EDM EntityDataReader Command Tree Entity SQL Query Conceptual Model Mapping Entity Framework EntityDataReader Command Tree Storage Model Entity Framework
Demo Model-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
Demo POCO
Demo Generate 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
A WCF Service Proxy Data Binding Entity Framework ObjectContext available ObjectContext not available Distributed system – WCF service SQL Server 2008
JSON/ XML HTTP/REST WCF  Data Service DataServiceContext Data Binding HTTP/REST Entity Framework ObjectContext available ObjectContext not available Distributed system – WCF Data service SQL Server 2008
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
DyCode www.dycode.com | office@dycode.com Dynamic IT Solutions for Optimal Business Value

More Related Content

What's hot

ADO.NET Entity Framework
ADO.NET Entity FrameworkADO.NET Entity Framework
ADO.NET Entity Framework
Doncho Minkov
 
Entity framework code first
Entity framework code firstEntity framework code first
Entity framework code first
Confiz
 
05 entity framework
05 entity framework05 entity framework
05 entity framework
glubox
 

What's hot (20)

Entity Framework - Entity Data Model (edm)
Entity Framework - Entity Data Model (edm)Entity Framework - Entity Data Model (edm)
Entity Framework - Entity Data Model (edm)
 
ADO.NET Entity Framework
ADO.NET Entity FrameworkADO.NET Entity Framework
ADO.NET Entity Framework
 
Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)
 
Entity Framework 4
Entity Framework 4Entity Framework 4
Entity Framework 4
 
Building nTier Applications with Entity Framework Services
Building nTier Applications with Entity Framework ServicesBuilding nTier Applications with Entity Framework Services
Building nTier Applications with Entity Framework Services
 
ADO.NET Entity Framework
ADO.NET Entity FrameworkADO.NET Entity Framework
ADO.NET Entity Framework
 
Entity Framework - Queries
Entity Framework -  QueriesEntity Framework -  Queries
Entity Framework - Queries
 
LINQ to Relational in Visual Studio 2008 SP1
LINQ to Relational in Visual Studio 2008 SP1LINQ to Relational in Visual Studio 2008 SP1
LINQ to Relational in Visual Studio 2008 SP1
 
Entity framework code first
Entity framework code firstEntity framework code first
Entity framework code first
 
Entity Framework - Object Services
Entity Framework -  Object ServicesEntity Framework -  Object Services
Entity Framework - Object Services
 
Introducing the Entity Framework
Introducing the Entity FrameworkIntroducing the Entity Framework
Introducing the Entity Framework
 
Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)
 
Microsoft Entity Framework
Microsoft Entity FrameworkMicrosoft Entity Framework
Microsoft Entity Framework
 
Linq
LinqLinq
Linq
 
MVC and Entity Framework
MVC and Entity FrameworkMVC and Entity Framework
MVC and Entity Framework
 
Java hibernate orm implementation tool
Java hibernate   orm implementation toolJava hibernate   orm implementation tool
Java hibernate orm implementation tool
 
05 entity framework
05 entity framework05 entity framework
05 entity framework
 
Introduction Of Linq , ASP.NET Training Ahmedabad, ASP.NET Course Ahmedabad
Introduction Of Linq , ASP.NET Training Ahmedabad, ASP.NET Course AhmedabadIntroduction Of Linq , ASP.NET Training Ahmedabad, ASP.NET Course Ahmedabad
Introduction Of Linq , ASP.NET Training Ahmedabad, ASP.NET Course Ahmedabad
 
05 entity framework
05 entity framework05 entity framework
05 entity framework
 
LINQ
LINQLINQ
LINQ
 

Similar to Entity Framework v2 Best Practices

What's New for Data?
What's New for Data?What's New for Data?
What's New for Data?
ukdpe
 
Ado.Net Data Services (Astoria)
Ado.Net Data Services (Astoria)Ado.Net Data Services (Astoria)
Ado.Net Data Services (Astoria)
Igor Moochnick
 

Similar to Entity Framework v2 Best Practices (20)

Poco Es Mucho: WCF, EF, and Class Design
Poco Es Mucho: WCF, EF, and Class DesignPoco Es Mucho: WCF, EF, and Class Design
Poco Es Mucho: WCF, EF, and Class Design
 
What's New for Data?
What's New for Data?What's New for Data?
What's New for Data?
 
Silverlight 2 for Developers - TechEd New Zealand 2008
Silverlight 2 for Developers - TechEd New Zealand 2008Silverlight 2 for Developers - TechEd New Zealand 2008
Silverlight 2 for Developers - TechEd New Zealand 2008
 
Ef Poco And Unit Testing
Ef Poco And Unit TestingEf Poco And Unit Testing
Ef Poco And Unit Testing
 
Entity Framework 4 In Microsoft Visual Studio 2010
Entity Framework 4 In Microsoft Visual Studio 2010Entity Framework 4 In Microsoft Visual Studio 2010
Entity Framework 4 In Microsoft Visual Studio 2010
 
Ado.Net Data Services (Astoria)
Ado.Net Data Services (Astoria)Ado.Net Data Services (Astoria)
Ado.Net Data Services (Astoria)
 
Overview of CSharp MVC3 and EF4
Overview of CSharp MVC3 and EF4Overview of CSharp MVC3 and EF4
Overview of CSharp MVC3 and EF4
 
Practical OData
Practical ODataPractical OData
Practical OData
 
Tdd,Ioc
Tdd,IocTdd,Ioc
Tdd,Ioc
 
Getting started with entity framework
Getting started with entity framework Getting started with entity framework
Getting started with entity framework
 
70487.pdf
70487.pdf70487.pdf
70487.pdf
 
Entity Framework V1 and V2
Entity Framework V1 and V2Entity Framework V1 and V2
Entity Framework V1 and V2
 
Entity framework and how to use it
Entity framework and how to use itEntity framework and how to use it
Entity framework and how to use it
 
ADO.NET Data Services
ADO.NET Data ServicesADO.NET Data Services
ADO.NET Data Services
 
MSDN Presents: Visual Studio 2010, .NET 4, SharePoint 2010 for Developers
MSDN Presents: Visual Studio 2010, .NET 4, SharePoint 2010 for DevelopersMSDN Presents: Visual Studio 2010, .NET 4, SharePoint 2010 for Developers
MSDN Presents: Visual Studio 2010, .NET 4, SharePoint 2010 for Developers
 
ADO.NET Entity Framework DevDays
ADO.NET Entity Framework DevDaysADO.NET Entity Framework DevDays
ADO.NET Entity Framework DevDays
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applications
 
MVC and Entity Framework 4
MVC and Entity Framework 4MVC and Entity Framework 4
MVC and Entity Framework 4
 
B_110500002
B_110500002B_110500002
B_110500002
 
Entity Framework v1 and v2
Entity Framework v1 and v2Entity Framework v1 and v2
Entity Framework v1 and v2
 

More from Andri Yadi

More from Andri Yadi (20)

AIoT: Intelligence on Microcontroller
AIoT: Intelligence on MicrocontrollerAIoT: Intelligence on Microcontroller
AIoT: Intelligence on Microcontroller
 
TechInAsia PDC 2019 - Unlocking The Potential of IoT with AI
TechInAsia PDC 2019 - Unlocking The Potential of IoT with AITechInAsia PDC 2019 - Unlocking The Potential of IoT with AI
TechInAsia PDC 2019 - Unlocking The Potential of IoT with AI
 
Global Azure Bootcamp 2019 - AIoT powered by Azure
Global Azure Bootcamp 2019 - AIoT powered by AzureGlobal Azure Bootcamp 2019 - AIoT powered by Azure
Global Azure Bootcamp 2019 - AIoT powered by Azure
 
Introduction to AIoT & TinyML - with Arduino
Introduction to AIoT & TinyML - with ArduinoIntroduction to AIoT & TinyML - with Arduino
Introduction to AIoT & TinyML - with Arduino
 
Opportunities & Challenges in IoT - Future of IoT industry in Indonesia 2019 ...
Opportunities & Challenges in IoT - Future of IoT industry in Indonesia 2019 ...Opportunities & Challenges in IoT - Future of IoT industry in Indonesia 2019 ...
Opportunities & Challenges in IoT - Future of IoT industry in Indonesia 2019 ...
 
Microsoft Azure-powered IoT & AI Solution To Help Farmer
Microsoft Azure-powered IoT & AI Solution To Help FarmerMicrosoft Azure-powered IoT & AI Solution To Help Farmer
Microsoft Azure-powered IoT & AI Solution To Help Farmer
 
IoT Connectivity with LoRa
IoT Connectivity with LoRaIoT Connectivity with LoRa
IoT Connectivity with LoRa
 
Ask the Expert: Internet of Things
Ask the Expert: Internet of ThingsAsk the Expert: Internet of Things
Ask the Expert: Internet of Things
 
Global Azure Bootcamp 2018 - Azure IoT Central
Global Azure Bootcamp 2018 - Azure IoT CentralGlobal Azure Bootcamp 2018 - Azure IoT Central
Global Azure Bootcamp 2018 - Azure IoT Central
 
Maker Movement toward IoT Ecosystem in Indonesia
Maker Movement toward IoT Ecosystem in IndonesiaMaker Movement toward IoT Ecosystem in Indonesia
Maker Movement toward IoT Ecosystem in Indonesia
 
IoT for Agriculture in a Nutshell: Technical Perspective
IoT for Agriculture in a Nutshell: Technical PerspectiveIoT for Agriculture in a Nutshell: Technical Perspective
IoT for Agriculture in a Nutshell: Technical Perspective
 
Road to Republic of IoT - IoT Technologies & Machine Learning
Road to Republic of IoT - IoT Technologies & Machine LearningRoad to Republic of IoT - IoT Technologies & Machine Learning
Road to Republic of IoT - IoT Technologies & Machine Learning
 
IoT Connectivity: The Technical & Potential
IoT Connectivity: The Technical & PotentialIoT Connectivity: The Technical & Potential
IoT Connectivity: The Technical & Potential
 
IT Solution through IoT Development
IT Solution through IoT DevelopmentIT Solution through IoT Development
IT Solution through IoT Development
 
Internet of Things - Technicals
Internet of Things - TechnicalsInternet of Things - Technicals
Internet of Things - Technicals
 
Global Azure Bootcamp 2017 - Azure IoT Hub with LoRa Connectivity
Global Azure Bootcamp 2017 - Azure IoT Hub with LoRa ConnectivityGlobal Azure Bootcamp 2017 - Azure IoT Hub with LoRa Connectivity
Global Azure Bootcamp 2017 - Azure IoT Hub with LoRa Connectivity
 
The state of NB-IoT in Indonesia
The state of NB-IoT in IndonesiaThe state of NB-IoT in Indonesia
The state of NB-IoT in Indonesia
 
Industrial IoT in a Nutshell
Industrial IoT in a NutshellIndustrial IoT in a Nutshell
Industrial IoT in a Nutshell
 
The Rise of Maker Movement in Indonesia
The Rise of Maker Movement in IndonesiaThe Rise of Maker Movement in Indonesia
The Rise of Maker Movement in Indonesia
 
Road to Republic of IoT - ESP32 Programming and LoRa
Road to Republic of IoT - ESP32 Programming and LoRaRoad to Republic of IoT - ESP32 Programming and LoRa
Road to Republic of IoT - ESP32 Programming and LoRa
 

Recently uploaded

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 

Recently uploaded (20)

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 

Entity Framework v2 Best Practices

  • 1. Entity framework v2Best Practices Microsoft Innovation Day 2010, May 11, 2010 AndriYadi| a@dycode.com CEO, DyCode | MVP, VSTO
  • 3. JSON WCF Data Services HTTP/REST Entity Framework Real-world Scenario SQL Server 2008
  • 5.
  • 6. INSERT UPDATE SELECT DELETE WHERE HAVING ORDER BY Then we code in SQL RIGHT JOIN COUNT UNION MIN/MAX LEFT
  • 7. ADO.NET code SqlCommandoCmd; SqlDataReaderoDR; string connString = ConfigurationManager. ConnectionStrings["OracleConnString"]. ConnectionString; SqlConnectionconn = 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();
  • 8. The Dilemma Software Architects & Developers Database Designers & Administrators
  • 9. ADO.NET ADO (1996) DAO (1992) RDO
  • 11. 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
  • 12. Why ORM? Development productivity Database independence Database portability
  • 13. Many attempts Typed Datasets Objectspaces ‘v1’ Objectspaces ‘v2’ Microsoft Business Framework WinFS Linq to SQL NHibernate  Will “RIP”  Not Microsoft’s
  • 14. ADO.NET Entity Framework Microsoft’s strategic technology Used in other Microsoft technologies (reporting services) V2 released with .NET 4.0 14
  • 15. 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
  • 18. IEnumerable<T> LINQ to Entities Entity SQL Query Entity Framework EDM EntityDataReader Command Tree Entity SQL Query Conceptual Model Mapping Entity Framework EntityDataReader Command Tree Storage Model Entity Framework
  • 20. 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;
  • 21. Explicit Loading Explicitly request to load the related objects customer.Orders.Load();
  • 22. Lazy Loading Related objects are loaded automatically for you when you access them
  • 23. 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
  • 24. 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
  • 25. Lazy Loading on POCO Declare lazy-loaded property as virtual Make sure to enable ContextOptions.LazyLoadingEnabled What’s under the hood?
  • 26. POCO Change tracking Snapshot-based Proxy-based
  • 28. Demo Generate EDM from database
  • 29. 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)
  • 30. EF v2 in Distributed System
  • 31. A WCF Service Proxy Data Binding Entity Framework ObjectContext available ObjectContext not available Distributed system – WCF service SQL Server 2008
  • 32. JSON/ XML HTTP/REST WCF Data Service DataServiceContext Data Binding HTTP/REST Entity Framework ObjectContext available ObjectContext not available Distributed system – WCF Data service SQL Server 2008
  • 33. So, WHAT’s NEW in EF2?
  • 34. 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
  • 35. 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
  • 36. 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
  • 37. 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
  • 38. 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
  • 39. DyCode www.dycode.com | office@dycode.com Dynamic IT Solutions for Optimal Business Value

Editor's Notes

  1. Dr. Edgar F. CoddE. F. Codd (Edgar F. &quot;Ted&quot; Codd) formed the concepts for organizing and accessing data that are embodied in the relational database, the predominant approach to data organization in today&apos;s business world. Critical of IBM&apos;s then current data management systems, Codd, as a young IBM programmer working in IBM&apos;s San Jose Research Lab in California in 1970, proposed that data be organized according to principles based on identified relations between various kinds of data. The data itself would be organized in two-dimensional (row and column) tables and specific items in a table could be related to data located in other tables. Codd saw the need to reduce or eliminate redundancy in data and to allow data to be accessed through logical rather than physical identification. One of Codd&apos;s key ideas was the process for organizing data into the appropriate number of tables, a process known asnormalization.
  2. - No separation between code and database schema. You still see a lot of SQL statements.- You also create dependency with specific database schema- SAP ERP database contains more than 30,000 tables.
  3. Maintainabity, security, efficiency andscalability let a DBA decideto:Splitdata of oneentityintoseveraltablesPutting data forseveral types of entitiesintosametableSupply projectionsthatlooseentity concepts thatmight have been present in tablestructures
  4. Typed Datasets – shippedObjectspaces ‘v1’ – never shippedObjectspaces ‘v2’ – never shippedMicrosoft Business Framework – never shippedWinFS – never shippedLinq to SQL – shipped, won’t be discontinuedLinq to Entities – shippedEntity Framework- shipped 
  5. Entity Framework- shipped 
  6. ERM = Entity-Relationship ModelEDM = Entity Data Model
  7. Explain the inner workings of the entity framework Three types of commands: LINQ to Entities against Object Services Materialization to Conceptual model classes or anonymous classes if projected Entity Sqlagaints Object Services Materialization if no projection + streamed data on row level Call model defines functions or specific Entity SQL functions. Entity Sql against Entity Client No materialization + streamed data on column levelExplain the path of commands…
  8. Do I need an Entity Data Model before I can use POCO?Yes – POCO support in Entity Framework 4.0 simply removes the need of having persistence specific concerns in your entity classes. There is still the need for you to have a CSDL/SSDL/MSL (collectively EDMX) metadata so that the Entity Framework is able to use your entities along with the metadata in order to enable data access. There is a separate effort that we are working on that will allow you to do true “code-first” development without the need to have a predefined EDMX model. A community preview of this feature will be released to the web in the coming months. We will roll this into the product the first chance we get. As always, your feedback will be helpful.How is metadata mapped when using POCO entities?In Entity Framework 3.5, both EntityObject and IPOCO based entities relied on the use of mapping attributes that were meant for decorating and mapping the entity types and properties back to the corresponding elements in the Conceptual model. Entity Framework 4.0 introduces convention based mapping for allowing mapping of Entity Types, Properties, Complex Types and Relationships back to the conceptual model without the need for explicit decoration. The simple rule here is that Entity Type names, Property names and Complex Types names used in your POCO classes must match those defined by the conceptual model. Namespace names are ignored and don’t have to match between the class definition and the conceptual model.Is Deferred (Lazy) Loading supported with POCO?Yes – Deferred (Lazy) loading is supported with POCO through the use of proxy types that are used to provide automatic lazy loading behavior on top of your POCO classes. This is something that we’ll cover when we get to deferred loading – until then know that eager loading via the use of “Include” is also supported, like so:
  9. The virtual keyword is used to modify a method or property declaration, in which case the method or the property is called a virtual member. The implementation of a virtual member can be changed by an overriding member in a derived class. When a virtual method is invoked, the run-time type of the object is checked for an overriding member. The overriding member in the most derived class is called, which might be the original member, if no derived class has overridden the member.What’s going on under the covers?The reason why this works is because when I marked my collection property as virtual, this allowed the Entity Framework to provide a proxy instance for my POCO type at runtime, and it is this proxy that does automatic deferred loading. The proxy instance is based on a type that derives from my own POCO entity class - so all functionality you have provided is preserved. From a developer point of view, this allows you to write persistence ignorant code even when deferred loading might be a requirement.Manual instantiation of Proxy instances for POCO entitiesIn order to enable creation of proxy instances for adding/attaching, you can use the CreateObject factory method on ObjectContext for creating entity instances:Category category = context.CreateObject&lt;Category&gt;();
  10. Snapshot based change tracking is what you get with pure POCO entities that don’t use proxies to handle change tracking. This is a simple change tracking solution that relies on complete snapshots of before and after values being maintained by the Entity Framework. These values are compared during SaveChanges to determine what has truly changed from their original values. In this model, unless you are using Lazy loading (must use virtual keyword), the runtime type of your entities is the same as you define for your POCO entities.Problem:Entity Framework’s Object State manager will go out of sync with your own object graph, before SaveChanges called. That’s because of no direct notification of changes to EF anytime your objects changeThecomparison during SaveChangesis relatively expensive when compared to the way change tracking works with EntityObject (non POCO) based entities.Proxy based Change Tracking is a different solution if you care about very efficient and up to date change tracking as you make changes to your entity values, relationships and object graph.You can leverage proxy based change tracking for a particular entity type if you declare all mapped properties on that entity type as virtual.Change Tracking proxies subclass your POCO entity class to provide you with this capability during runtime without requiring you to implement the IPOCO interfaces yourself.How?Your class must be public, non-abstract or non-sealed. Your class must also implement public virtual getters/setters for all properties that are persisted/mapped. Finally, you must declare collection based relationship navigation properties as ICollection&lt;T&gt; only. They cannot be a concrete implementation or another interface that derives from ICollection&lt;T&gt; (a difference from the Deferred Loading proxy)
  11. http://www.robbagby.com/entity-framework/is-lazy-loading-in-ef-4-evil-or-the-second-coming/
  12. T4 = Text Template Transformation Toolkit