Using SPAN to query entities in Entity Framework
|
By default, when querying entities, you need to explicitly use the Load method to get related data. This is often called "lazy loading" and ensures that you only get what you ask for rather than having a query return ALL related data automatically. This is a good default; but often you know that you want the related data in advance and don't want to pay for the extra round trips to the database. The new SPAN method forces an entity to include specified related data during a query so that you don't have to load after the fact. nwEntities.Customers.Span.Include("Orders") The SPAN method is called in a way that tells the object context that whenever you are querying for Customers, include the Orders as well. That also means that you need to turn that off if you don't want that rule to exist for the lifetime of object context. You can reset the Span for that entity so that it will stop pulling in the orders implicitly. nwEntities.Customers.Span.Reset() That's the concept, at least. I'm not getting the results I would expect with this (a second query without using Reset does not give me orders (which do exist and will appear if I call Load)). But it is a CTP... so I can live with it for now and will point it out in the forums. Here is an example of using load to get orders for a group of customers Dim custs = nwEntities.CreateQuery(Of Customers)("Select value c from customers as c where c.Country='Spain'") and an example of bringing the orders in during the first pass Dim custsSpain = nwEntities.CreateQuery(Of Customers)("Select value c from customers as c where c.Country='Spain'") For Each cust As Customers In custsSpain |


Comments (1)
Thanks, Julia. I asked some members of the team about lazy loading at Tech Ed last month. None of them mentioned using span. This should please a lot of people, once they get the bugs out.
Cheers,
++Alan
Posted by Alan Stevens | July 5, 2007 10:01 PM