SlideShare ist ein Scribd-Unternehmen logo
1 von 25
VVS14:Entity Framework Tips & Tricks Julie Lerman www.thedatafarm.com jlerman@thedatafarm.com twitter: @JulieLermanVT
Julie Lerman website theDataFarm.com blog & twitter theDataFarm.com/blog@julielermanVT book web site LearnEntityFramework.com consultant/mentor Microsoft MVP, INETA Speaker,ASPInsider, MCP, VTdotNET Leader
Tips & Tricks  Version 1 Pain Points Fixed in EF4 Query Helpers Use ObjectQuery methods with LINQ to Entities Find Exception Handling Details Create Generic Queries Encapsulate Query Execution Improve Query Performance
!      V1 Model hides Foreign Key
Get FK value from Entity Reference
Set FK Value through Entity Ref from Single EntityKey Property Order.CustomerReference.EntityKey =  new EntityKey("MyEntities.Customers", "PersonID", 1) from Multiple EntityKey Properties vareKeyValues =      new KeyValuePair<string, object>[] {          new KeyValuePair<string, object>(“PropertyA", 12),          new KeyValuePair<string, object>(“PropertyB", 103)          }; EntityKey ekey= new EntityKey(“MyEntities", eKeyValues); instance.EntityRef.EntityKey=ekey;
     V1: Undesirable Store Queries LINQ to Entities Query From p In context.PeopleWhere p.LastName.StartsWith(“K") Resulting T-SQL Query SELECT  [Extent1].[PersonID] AS [PersonID],  ... WHERE (CAST(CHARINDEX(N'T', Extent1].[LastName])        AS int)) = 1 !
Control Store Query with ESQL      Entity SQL SELECT VALUE p FROM EFEntities.People AS p WHERE p.LastName LIKE “T%” Query Builder Methodscontext.People.Where("it.LastName LIKE 'T%'")      Resulting T-SQL SELECT [Extent1].[PersonID] AS [PersonID],  WHERE [Extent1].[LastName] LIKE 'T%'
Queries in Entity Framework 4 Huge improvements to generated queries Contains added to LINQ to Entities & ESQL StartsWith, EndsWith,Contains LIKE %% Much More.. See blogs.msdn.com/adonet August 5, 2009 post
Awesome Third Party Tools LINQPad Test Queries LINQ, L2S, L2E, ESQL EFProf Capture *All*  Database Activity
     V1: Random columns from Sprocs CREATE PROCEDURE OrdersBySalesPersonbyDate AS SELECT  MIN(Person.FirstName) as First,                 MIN(Person.LastName) as Last,               COUNT(OrderId) as OrderCount FROM … Requires lots of manual editing of the model, MSL and SSDL to create an entity that matches the return value !
Use Views in Place of Sprocs CREATE VIEW OrdersBySalesPersonbyDate AS SELECT  MIN(Person.FirstName) as First,                 MIN(Person.LastName) as Last,               COUNT(Orderid) as OrderCount FROM … Wizard creates all entity metadata elements  Other benefits View is composable Use in queries Change Tracking (use stored procs for Ins/Upd/Del)
Stored Procs in Entity Framework 4 Major support improvements Map functions to complex types Designer can discover result shapes and auto-create the complex types for you
Country Reference List List<Customer> GetCustomers()      {  return context.Customers.OrderBy(c => c.LastName)                               .ToList(); } Account Type Reference List   List<AccountType> GetAccountTypes()     {  return context.AccountTypes.OrderBy(a => a.TypeName)                                 .ToList(); } Product Reference List  List<Product> GetProducts()     {  return context.Products.OrderBy(p => p. Name)                             .ToList(); } !        Redundant L2E Queries
Build Reusable, Generic Queries public static List<TEntity> GetReferenceList<TEntity>    (this ObjectContext context) context.GetReferenceList<Country> context.GetReferenceList(Of AccountType) context.GetReferenceList<Product>
var query=from p in context.People select p; try  { var people=query.ToList(); } catch (EntityException)  { ... } Catch (CommandExecutionException)  { ... } var query2=from o in context.Orders select o; try  { var orders =query2.ToList(); } catch (EntityException)  { ... } Catch (CommandExecutionException)  { ... } !       Redundant code around queries
Encapsulate Query Execution Reusable Repository Methods public List<TEntity> ExecuteList<TEntity>    (ObjectQuery<TEntity> objectQuery) public List<TEntity> ExecuteList<TEntity>   (IQueryable<TEntity> L2EQuery) Calling Reusable Methods IEnumerable<Person> L2EQuery = from p in context.People                                select p; List<Person> people = dal.ExecuteList<Person>(L2EQuery); ObjectQuery oQuery = context.Orders; List<Order> orderList = dal.ExecuteList<Order>(oQuery);
s Order B ? Person A Person B Order A db Error ? Person D Order C ? Order D Person C ! UpdateExceptions Anonymity
ObjectStateEntry & Entity Instance provided in UpdateException
Pre-Compile L2E Queries Pre-Compiled Query LINQ to Entities Query Store Query
      Web Sites Lose      Pre-Compiled L2E Queries ,[object Object]
Pre-Compilation is repeated each time
App process loses benefit of pre-compilation
Big performance loss!
Cache Pre-Compiled Query Func Class Level Static Function static Func<MyEntities, IQueryable<Customer>> customerPCQ;  Class Constructor public CustomerProvider()  {   if (customerPCQ == null)   { customerPCQ = CompiledQuery.Compile<MyEntities,                                         IQueryable<Customer>>                   (ctx => from cust in ctx.Customers                           where cust.Orders.Any()                           select cust                   );     } }

Weitere ähnliche Inhalte

Was ist angesagt?

Entity Framework: Code First and Magic Unicorns
Entity Framework: Code First and Magic UnicornsEntity Framework: Code First and Magic Unicorns
Entity Framework: Code First and Magic Unicorns
Richie Rump
 
Entity framework code first
Entity framework code firstEntity framework code first
Entity framework code first
Confiz
 
ADO.NET Entity Framework
ADO.NET Entity FrameworkADO.NET Entity Framework
ADO.NET Entity Framework
Doncho Minkov
 
Ado.Net Data Services (Astoria)
Ado.Net Data Services (Astoria)Ado.Net Data Services (Astoria)
Ado.Net Data Services (Astoria)
Igor Moochnick
 

Was ist angesagt? (20)

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 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
 
Entity Framework: Code First and Magic Unicorns
Entity Framework: Code First and Magic UnicornsEntity Framework: Code First and Magic Unicorns
Entity Framework: Code First and Magic Unicorns
 
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
 
Introducing the Entity Framework
Introducing the Entity FrameworkIntroducing the Entity Framework
Introducing the Entity Framework
 
Entity Framework v2 Best Practices
Entity Framework v2 Best PracticesEntity Framework v2 Best Practices
Entity Framework v2 Best Practices
 
Getting started with entity framework
Getting started with entity framework Getting started with entity framework
Getting started with entity framework
 
Ef code first
Ef code firstEf code first
Ef code first
 
Entity Framework Database and Code First
Entity Framework Database and Code FirstEntity Framework Database and Code First
Entity Framework Database and Code First
 
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
 
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
 
Entity framework
Entity frameworkEntity framework
Entity framework
 
Entity Framework 4 In Microsoft Visual Studio 2010 - ericnel
Entity Framework 4 In Microsoft Visual Studio 2010 - ericnelEntity Framework 4 In Microsoft Visual Studio 2010 - ericnel
Entity Framework 4 In Microsoft Visual Studio 2010 - ericnel
 
ADO.NET Entity Framework
ADO.NET Entity FrameworkADO.NET Entity Framework
ADO.NET Entity Framework
 
Building nTier Applications with Entity Framework Services (Part 2)
Building nTier Applications with Entity Framework Services (Part 2)Building nTier Applications with Entity Framework Services (Part 2)
Building nTier Applications with Entity Framework Services (Part 2)
 
Ado.Net Data Services (Astoria)
Ado.Net Data Services (Astoria)Ado.Net Data Services (Astoria)
Ado.Net Data Services (Astoria)
 
ADO.NET Data Services
ADO.NET Data ServicesADO.NET Data Services
ADO.NET Data Services
 
Introduction to Core Java Programming
Introduction to Core Java ProgrammingIntroduction to Core Java Programming
Introduction to Core Java Programming
 
C# advanced topics and future - C#5
C# advanced topics and future - C#5C# advanced topics and future - C#5
C# advanced topics and future - C#5
 

Ähnlich wie Lerman Vvs14 Ef Tips And Tricks

CiklumJavaSat_15112011:Alex Kruk VMForce
CiklumJavaSat_15112011:Alex Kruk VMForceCiklumJavaSat_15112011:Alex Kruk VMForce
CiklumJavaSat_15112011:Alex Kruk VMForce
Ciklum Ukraine
 
Intention Oriented Model Interaction
Intention Oriented Model InteractionIntention Oriented Model Interaction
Intention Oriented Model Interaction
Yasir Karam
 

Ähnlich wie Lerman Vvs14 Ef Tips And Tricks (20)

Wcf data services
Wcf data servicesWcf data services
Wcf data services
 
java ee 6 Petcatalog
java ee 6 Petcatalogjava ee 6 Petcatalog
java ee 6 Petcatalog
 
Generalized Functors - Realizing Command Design Pattern in C++
Generalized Functors - Realizing Command Design Pattern in C++Generalized Functors - Realizing Command Design Pattern in C++
Generalized Functors - Realizing Command Design Pattern in C++
 
Introduction to JSF
Introduction toJSFIntroduction toJSF
Introduction to JSF
 
EclipseCon 2008: Fundamentals of the Eclipse Modeling Framework
EclipseCon 2008: Fundamentals of the Eclipse Modeling FrameworkEclipseCon 2008: Fundamentals of the Eclipse Modeling Framework
EclipseCon 2008: Fundamentals of the Eclipse Modeling Framework
 
JavaEE Spring Seam
JavaEE Spring SeamJavaEE Spring Seam
JavaEE Spring Seam
 
CiklumJavaSat_15112011:Alex Kruk VMForce
CiklumJavaSat_15112011:Alex Kruk VMForceCiklumJavaSat_15112011:Alex Kruk VMForce
CiklumJavaSat_15112011:Alex Kruk VMForce
 
Tdd,Ioc
Tdd,IocTdd,Ioc
Tdd,Ioc
 
Ruby on rails
Ruby on rails Ruby on rails
Ruby on rails
 
jBPM5 in action - a quickstart for developers
jBPM5 in action - a quickstart for developersjBPM5 in action - a quickstart for developers
jBPM5 in action - a quickstart for developers
 
ADO.NET Entity Framework by Jose A. Blakeley and Michael Pizzo
ADO.NET Entity Framework by Jose A. Blakeley and Michael PizzoADO.NET Entity Framework by Jose A. Blakeley and Michael Pizzo
ADO.NET Entity Framework by Jose A. Blakeley and Michael Pizzo
 
Introducing Struts 2
Introducing Struts 2Introducing Struts 2
Introducing Struts 2
 
Tech_Implementation of Complex ITIM Workflows
Tech_Implementation of Complex ITIM WorkflowsTech_Implementation of Complex ITIM Workflows
Tech_Implementation of Complex ITIM Workflows
 
Struts2
Struts2Struts2
Struts2
 
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
 
Intention Oriented Model Interaction
Intention Oriented Model InteractionIntention Oriented Model Interaction
Intention Oriented Model Interaction
 
A Complete Tour of JSF 2
A Complete Tour of JSF 2A Complete Tour of JSF 2
A Complete Tour of JSF 2
 
B_110500002
B_110500002B_110500002
B_110500002
 
Os Johnson
Os JohnsonOs Johnson
Os Johnson
 
Apex Enterprise Patterns: Building Strong Foundations
Apex Enterprise Patterns: Building Strong FoundationsApex Enterprise Patterns: Building Strong Foundations
Apex Enterprise Patterns: Building Strong Foundations
 

Mehr von Julie Lerman

Julie Lerman: Entity Framework FTQs (Frequently Tweeted Questions)
Julie Lerman: Entity Framework FTQs (Frequently Tweeted Questions)Julie Lerman: Entity Framework FTQs (Frequently Tweeted Questions)
Julie Lerman: Entity Framework FTQs (Frequently Tweeted Questions)
Julie Lerman
 
Julie Lerman Entity Framework in the Enterprise (Boston Code Camp March 2013)
Julie Lerman Entity Framework in the Enterprise (Boston Code Camp March 2013)Julie Lerman Entity Framework in the Enterprise (Boston Code Camp March 2013)
Julie Lerman Entity Framework in the Enterprise (Boston Code Camp March 2013)
Julie Lerman
 
Working With Sql Azure from Entity Framework On-Premises (Julia Lerman)
Working With Sql Azure from Entity Framework On-Premises (Julia Lerman)Working With Sql Azure from Entity Framework On-Premises (Julia Lerman)
Working With Sql Azure from Entity Framework On-Premises (Julia Lerman)
Julie Lerman
 

Mehr von Julie Lerman (20)

EF Core in Containerized ASP.NET Core APIs
EF Core in Containerized ASP.NET Core APIsEF Core in Containerized ASP.NET Core APIs
EF Core in Containerized ASP.NET Core APIs
 
Domain-Driven Design with Tender Loving Care (DDD with TLC)
Domain-Driven Design with Tender Loving Care (DDD with TLC)Domain-Driven Design with Tender Loving Care (DDD with TLC)
Domain-Driven Design with Tender Loving Care (DDD with TLC)
 
What's New in Visual Studio 2017
What's New in Visual Studio 2017What's New in Visual Studio 2017
What's New in Visual Studio 2017
 
A Tour of EF Core's (1.1) Most Interesting & Important Features
A Tour of EF Core's (1.1) Most Interesting & Important FeaturesA Tour of EF Core's (1.1) Most Interesting & Important Features
A Tour of EF Core's (1.1) Most Interesting & Important Features
 
EF6 or EF Core? How Do I Choose?
EF6 or EF Core? How Do I Choose?EF6 or EF Core? How Do I Choose?
EF6 or EF Core? How Do I Choose?
 
Microsoft for developers open source and cross platform
Microsoft for developers  open source and cross platformMicrosoft for developers  open source and cross platform
Microsoft for developers open source and cross platform
 
Entity Framework and Domain Driven Design
Entity Framework and Domain Driven DesignEntity Framework and Domain Driven Design
Entity Framework and Domain Driven Design
 
RavenDB Overview
RavenDB OverviewRavenDB Overview
RavenDB Overview
 
Julie Lerman: Entity Framework FTQs (Frequently Tweeted Questions)
Julie Lerman: Entity Framework FTQs (Frequently Tweeted Questions)Julie Lerman: Entity Framework FTQs (Frequently Tweeted Questions)
Julie Lerman: Entity Framework FTQs (Frequently Tweeted Questions)
 
Julie Lerman Entity Framework in the Enterprise (Boston Code Camp March 2013)
Julie Lerman Entity Framework in the Enterprise (Boston Code Camp March 2013)Julie Lerman Entity Framework in the Enterprise (Boston Code Camp March 2013)
Julie Lerman Entity Framework in the Enterprise (Boston Code Camp March 2013)
 
Entity Framework Today (May 2012)
Entity Framework Today (May 2012)Entity Framework Today (May 2012)
Entity Framework Today (May 2012)
 
Working With Sql Azure from Entity Framework On-Premises (Julia Lerman)
Working With Sql Azure from Entity Framework On-Premises (Julia Lerman)Working With Sql Azure from Entity Framework On-Premises (Julia Lerman)
Working With Sql Azure from Entity Framework On-Premises (Julia Lerman)
 
Perspectives on Entity Framework, Julie Lerman
Perspectives on Entity Framework, Julie LermanPerspectives on Entity Framework, Julie Lerman
Perspectives on Entity Framework, Julie Lerman
 
Entity Framework NYC Firestarter
Entity Framework NYC FirestarterEntity Framework NYC Firestarter
Entity Framework NYC Firestarter
 
Getting Persistence Ignorant with Entity Framework, Julie Lerman
Getting Persistence Ignorant with Entity Framework, Julie LermanGetting Persistence Ignorant with Entity Framework, Julie Lerman
Getting Persistence Ignorant with Entity Framework, Julie Lerman
 
Persistence Ignorance in Entity Framework 4, Julie Lerman
Persistence Ignorance in Entity Framework 4, Julie LermanPersistence Ignorance in Entity Framework 4, Julie Lerman
Persistence Ignorance in Entity Framework 4, Julie Lerman
 
Persistence Ignorance in Entity Framework 4, Julie Lerman
Persistence Ignorance in Entity Framework 4, Julie LermanPersistence Ignorance in Entity Framework 4, Julie Lerman
Persistence Ignorance in Entity Framework 4, Julie Lerman
 
Entity Framework 4 and WCF
Entity Framework 4 and WCFEntity Framework 4 and WCF
Entity Framework 4 and WCF
 
Julie Lerman Agile Entity Framework (March 2010)
Julie Lerman Agile Entity Framework (March 2010)Julie Lerman Agile Entity Framework (March 2010)
Julie Lerman Agile Entity Framework (March 2010)
 
AgileEntity Framework 4
AgileEntity Framework 4AgileEntity Framework 4
AgileEntity Framework 4
 

Kürzlich hochgeladen

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
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
 

Kürzlich hochgeladen (20)

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
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
 
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
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
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
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
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
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
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
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.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
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 

Lerman Vvs14 Ef Tips And Tricks

  • 1. VVS14:Entity Framework Tips & Tricks Julie Lerman www.thedatafarm.com jlerman@thedatafarm.com twitter: @JulieLermanVT
  • 2. Julie Lerman website theDataFarm.com blog & twitter theDataFarm.com/blog@julielermanVT book web site LearnEntityFramework.com consultant/mentor Microsoft MVP, INETA Speaker,ASPInsider, MCP, VTdotNET Leader
  • 3. Tips & Tricks Version 1 Pain Points Fixed in EF4 Query Helpers Use ObjectQuery methods with LINQ to Entities Find Exception Handling Details Create Generic Queries Encapsulate Query Execution Improve Query Performance
  • 4. ! V1 Model hides Foreign Key
  • 5. Get FK value from Entity Reference
  • 6. Set FK Value through Entity Ref from Single EntityKey Property Order.CustomerReference.EntityKey = new EntityKey("MyEntities.Customers", "PersonID", 1) from Multiple EntityKey Properties vareKeyValues = new KeyValuePair<string, object>[] { new KeyValuePair<string, object>(“PropertyA", 12), new KeyValuePair<string, object>(“PropertyB", 103) }; EntityKey ekey= new EntityKey(“MyEntities", eKeyValues); instance.EntityRef.EntityKey=ekey;
  • 7. V1: Undesirable Store Queries LINQ to Entities Query From p In context.PeopleWhere p.LastName.StartsWith(“K") Resulting T-SQL Query SELECT [Extent1].[PersonID] AS [PersonID], ... WHERE (CAST(CHARINDEX(N'T', Extent1].[LastName]) AS int)) = 1 !
  • 8. Control Store Query with ESQL Entity SQL SELECT VALUE p FROM EFEntities.People AS p WHERE p.LastName LIKE “T%” Query Builder Methodscontext.People.Where("it.LastName LIKE 'T%'") Resulting T-SQL SELECT [Extent1].[PersonID] AS [PersonID], WHERE [Extent1].[LastName] LIKE 'T%'
  • 9. Queries in Entity Framework 4 Huge improvements to generated queries Contains added to LINQ to Entities & ESQL StartsWith, EndsWith,Contains LIKE %% Much More.. See blogs.msdn.com/adonet August 5, 2009 post
  • 10. Awesome Third Party Tools LINQPad Test Queries LINQ, L2S, L2E, ESQL EFProf Capture *All* Database Activity
  • 11. V1: Random columns from Sprocs CREATE PROCEDURE OrdersBySalesPersonbyDate AS SELECT MIN(Person.FirstName) as First, MIN(Person.LastName) as Last, COUNT(OrderId) as OrderCount FROM … Requires lots of manual editing of the model, MSL and SSDL to create an entity that matches the return value !
  • 12. Use Views in Place of Sprocs CREATE VIEW OrdersBySalesPersonbyDate AS SELECT MIN(Person.FirstName) as First, MIN(Person.LastName) as Last, COUNT(Orderid) as OrderCount FROM … Wizard creates all entity metadata elements Other benefits View is composable Use in queries Change Tracking (use stored procs for Ins/Upd/Del)
  • 13. Stored Procs in Entity Framework 4 Major support improvements Map functions to complex types Designer can discover result shapes and auto-create the complex types for you
  • 14. Country Reference List List<Customer> GetCustomers() { return context.Customers.OrderBy(c => c.LastName) .ToList(); } Account Type Reference List List<AccountType> GetAccountTypes() { return context.AccountTypes.OrderBy(a => a.TypeName) .ToList(); } Product Reference List List<Product> GetProducts() { return context.Products.OrderBy(p => p. Name) .ToList(); } ! Redundant L2E Queries
  • 15. Build Reusable, Generic Queries public static List<TEntity> GetReferenceList<TEntity> (this ObjectContext context) context.GetReferenceList<Country> context.GetReferenceList(Of AccountType) context.GetReferenceList<Product>
  • 16. var query=from p in context.People select p; try { var people=query.ToList(); } catch (EntityException) { ... } Catch (CommandExecutionException) { ... } var query2=from o in context.Orders select o; try { var orders =query2.ToList(); } catch (EntityException) { ... } Catch (CommandExecutionException) { ... } ! Redundant code around queries
  • 17. Encapsulate Query Execution Reusable Repository Methods public List<TEntity> ExecuteList<TEntity> (ObjectQuery<TEntity> objectQuery) public List<TEntity> ExecuteList<TEntity> (IQueryable<TEntity> L2EQuery) Calling Reusable Methods IEnumerable<Person> L2EQuery = from p in context.People select p; List<Person> people = dal.ExecuteList<Person>(L2EQuery); ObjectQuery oQuery = context.Orders; List<Order> orderList = dal.ExecuteList<Order>(oQuery);
  • 18. s Order B ? Person A Person B Order A db Error ? Person D Order C ? Order D Person C ! UpdateExceptions Anonymity
  • 19. ObjectStateEntry & Entity Instance provided in UpdateException
  • 20. Pre-Compile L2E Queries Pre-Compiled Query LINQ to Entities Query Store Query
  • 21.
  • 23. App process loses benefit of pre-compilation
  • 25. Cache Pre-Compiled Query Func Class Level Static Function static Func<MyEntities, IQueryable<Customer>> customerPCQ; Class Constructor public CustomerProvider() { if (customerPCQ == null) { customerPCQ = CompiledQuery.Compile<MyEntities, IQueryable<Customer>> (ctx => from cust in ctx.Customers where cust.Orders.Any() select cust ); } }
  • 26. Summary Some of the big EFV1 pain points are gone in EF4 Don’t ignore the power of Entity SQL Dig into the APIs to leverage the real power of EF
  • 27. Julie Lerman website theDataFarm.com blog & twitter theDataFarm.com/blog@julielermanVT book web site LearnEntityFramework.com consultant/mentor Microsoft MVP, INETA Speaker,ASPInsider, MCP, VTdotNET Leader
  • 28. Resources mentioned in this talk Learnentityframework.com Blogs.msdn.com/adonet,/efdesign, /alexj www.linqpad.net EF Profiler: http://ayende.com/Blog/category/551.aspx