Download presentation
Presentation is loading. Please wait.
1
Tech·Ed North America 2009 6/5/2018 6:10 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.
2
The ADO.NET Entity Framework: Tips & Tricks
Tech·Ed North America 2009 6/5/2018 6:10 PM The ADO.NET Entity Framework: Tips & Tricks Julie Lerman The Data Farm DTL312 © 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.
3
Julie Lerman Mentor/Consultant jlerman@thedatafarm.com
thedatafarm.com/blog LearnEntityFramework.com
4
10 Tips & Tricks Solving Pain Points Foreign Keys: Reading : Writing
: Set Default Value Improve Inefficient Store Queries Use Random Results from Stored Procedures Use ObjectQuery methods with L2E Using EF More Effectively Create Generic Queries Find Exception Handling Details Encapsulate Query Execution Improve Query Performance
5
EF Model Hides Foreign Key
! EF Model Hides Foreign Key
6
1. Get FK Value When No Reference Object Is Available
7
2. Set Reference without Ref Object
from Single EntityKey Property Order.CustomerReference.EntityKey = new EntityKey("MyEntities.Customers", "PersonID", 1) from Multiple EntityKey Properties var eKeyValues = 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;
8
3. Set Default Entity Reference Value
Create Constructor in Entity's Partial Class C# Public Customer() { CustomerTypeReference.EntityKey = new EntityKey("MyEntities.CustomerTypes", “TypeID", 1) } VB Public Sub New() CustomerTypeReference.EntityKey = New EntityKey("MyEntities.CustomerTypes", “TypeID", 1) End Sub
9
Undesirable Store Queries
! Undesirable Store Queries LINQ to Entities Query From p In context.People Where p.LastName.StartsWith(“K") Resulting T-SQL Query SELECT [Extent1].[PersonID] AS [PersonID], ... WHERE (CAST(CHARINDEX(N'T', Extent1].[LastName]) AS int)) = 1
10
4. Control Store Query w/ ESQL
Entity SQL SELECT VALUE p FROM EFEntities.People AS p WHERE p.LastName LIKE “T%” Query Builder Methods context.People.Where("it.LastName LIKE 'T%'") Resulting T-SQL SELECT [Extent1].[PersonID] AS [PersonID], WHERE [Extent1].[LastName] LIKE 'T%'
11
Bonus Tip! Testing ESQL Expressions
eSql Blast! code.msdn.com/adonetefx
12
Stored Procs Return Non-Entity
! Stored Procs Return Non-Entity 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
13
5. 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 DML)
14
ObjectQuery Special Methods in L2E
! ObjectQuery Special Methods in L2E Include from p in context.Orders.Include(“Customer”) select p OfType from p in context.People.OfType<Customer> MergeOption context.People.MergeOption=MergeOption.NoTracking; from p in context.People select p; Execute ??? ToTraceString
15
6. Cast L2E to Get ObjectQuery Methods
var l2eQuery=from c in context.Customers select c ; var storeSQL=((ObjectQuery)l2eQuery).ToTraceString(); VB Dim l2eQuery=From c In context.Customers Select c Dim storeSQL = CType(l2eQuery, ObjectQuery).ToTraceString
16
! Redundant L2E Queries Country Reference List
List<Country> GetCountries() { return context.Countries.OrderBy(c => c.Name) .ToList(); } Account Type Reference List List<AccountType> GetAccountTypes() { return context.AccountTypes.OrderBy(a => a.TypeName) Product Reference List List<Product> GetProducts() { return context.Products.OrderBy(p => p. Name)
17
7. Build Reusable, Generic Queries
public static List<TEntity> GetReferenceList<TEntity> (this ObjectContext context) context.GetReferenceList<Country> context.GetReferenceList(Of AccountType) context.GetReferenceList<Product>
18
UpdateExceptions Anonymity
! UpdateExceptions Anonymity s Order B ? Person A Person B Order A db Error ? Person D Order C ? Order D Person C
19
8. ObjectStateEntry & Entity Instance Are Provided in UpdateExceptions
20
Redundant Code around Queries
! Redundant Code around Queries 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)
21
9. Encapsulate Query Execution
Reusable Repository Methods public List<TEntity> ExecuteList<TEntity> (ObjectQuery<TEntity> objectQuery) (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);
22
Bonus Tip! Pre-Compile L2E Queries
LINQ to Entities Query PreCompiled Query Store Query
23
Web Sites Lose Pre-Compiled L2E Queries
! Web Sites Lose Pre-Compiled L2E Queries Short-lived ObjectContext used to compile Pre-Compilation is repeated each time App process loses benefit of pre-compilation Big performance loss
24
10. 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 ); }
25
EF4 Removes Some of the Pain
Solving Pain Points Foreign Keys: Reading : Writing : Set Default Value Improve Inefficient Store Queries Use Random Results from Stored Procedures Use ObjectQuery methods with L2E Using EF More Effectively Create Generic Queries Find Exception Handling Details Encapsulate Query Execution Improve Query Performance
26
Contact Julie Lerman jlerman@thedatafarm.com thedatafarm.com/blog
LearnEntityFramework.com
27
question & answer
28
Resources Required Slide Speakers, www.microsoft.com/teched
TechEd 2009 is not producing a DVD. Please announce that attendees can access session recordings at TechEd Online. Resources Sessions On-Demand & Community Microsoft Certification & Training Resources Resources for IT Professionals Resources for Developers Microsoft Certification and Training Resources
29
Track Resources Visit the DPR TLC for a chance to win a copy of Visual Studio Team Suite. Daily drawing occurs every day in the TLC at 4:15pm. Stop by for a raffle ticket Please visit us in the TLC blue area
30
Complete an evaluation on CommNet and enter to win!
Required Slide Complete an evaluation on CommNet and enter to win!
31
Required Slide 6/5/2018 6:10 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. © 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.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.