Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using DbSet<TEntity>.Local Property in Entity Framework

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?

like image 858
Kryszal Avatar asked Apr 18 '15 11:04

Kryszal


People also ask

What does DbSet TEntity class represent in Entity Framework?

A DbSet represents the collection of all entities in the context, or that can be queried from the database, of a given type. DbSet objects are created from a DbContext using the DbContext.

What is DbSet local?

The Local property of DbSet provides simple access to the entities of the set that are currently being tracked by the context and have not been marked as Deleted. Accessing the Local property never causes a query to be sent to the database. This means that it is usually used after a query has already been performed.

What is the difference between DbSet and DbContext?

Intuitively, a DbContext corresponds to your database (or a collection of tables and views in your database) whereas a DbSet corresponds to a table or view in your database.

Is DbSet part of DbContext?

The DbSet class represents an entity set that can be used for create, read, update, and delete operations. The context class (derived from DbContext ) must include the DbSet type properties for the entities which map to database tables and views.


1 Answers

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.

like image 177
mr100 Avatar answered Sep 28 '22 04:09

mr100