7

Following MSDN documentation we can use Local property to get local/cached data directly from the context without additional requests to a data source:

Gets an ObservableCollection that represents a local view of all Added, Unchanged, and Modified entities in this set.
(...)
This property can be used for data binding by populating the set with data, for example by using the Load extension method, and then binding to the local data through this property.

The problem is, that code is not working (Local is empty):

context.SampleEntities.Select(x => new { x.A, x.B }).Load();
// context.SampleEntities.Local.Count is 0

But in this case, it seems working correctly:

context.SampleEntities.Load();
// context.SampleEntities.Local.Count is not 0

Maybe someone can explain what is the correct way to use Local property?
What is more, how to use it with partially loaded entities, like in the case above?

Kryszal
  • 1,663
  • 14
  • 20
  • 3
    EF has nowhere to store these projected queries: you don't have a collection that holds just these fields. I would assume that it is simply impossible to cache those locally for this reason. – Jeroen Vannevel Apr 18 '15 at 11:50
  • But I think it should be still the same collection (SampleEntities) where entities are not fully loaded (e.g. some fields are empty). My logic is, the result of the SQL query should be stored in DbSet too (where really important is the entity key and the entity state) or in the alternate way, partially loaded entities are not cached at all. So, do you indicate the second scenario is the right one? – Kryszal Apr 18 '15 at 12:21

1 Answers1

7

This is expected behaviour. Local caches entities that were loaded by you from database during lifetime of DbContext object. With query:

context.SampleEntities.Select(x => new { x.A, x.B })

you are loading to your application memory no SampleEntity object, but only its proeprties A and B. Select is as well translated to sql query to limit rows returned from the query and thus increase performance.

mr100
  • 4,340
  • 2
  • 26
  • 38
  • OK, thank you. I've found similar explanation in that thread: http://stackoverflow.com/questions/12668469/entity-framework-partial-load So I see, objects returned from Select method are not tracked at all. – Kryszal Apr 18 '15 at 12:44