ygoe ygoe - 3 months ago 16
C# Question

DbSet: missing added item

In a

DbSet
entity collection of Entity Framework (6.1.3), when I add a new item, it is not returned from the collection afterwards. This is strange and unexpected. Here's some gathered sample code:

dbContext.Entities.ToArray();
// contains 3 entries
dbContext.Entities.Add(new Entity());
dbContext.Entities.ToArray();
// still contains 3 entries


How can this be? When I query
dbContext.Entities
in the immediate window in Visual Studio, it says something like "Local: Count = 4". Why does it hide the new item from me?

Update: If this collection doesn't do the obvious thing – returning what was added before – what do I need to do instead? It must return all records from the database when called first, and it must also include all changes (add and remove) when called later.
SaveChanges
is only called when the user has finished editing things. The collection is needed before that!
SaveChanges
might also be called somewhere in between when the user is finished editing, but the code might return and the view be displayed again at a later time.

Answer

A DbSet has a property Local. This is an ObservableCollection that contains all elements. The DbSet object itself represents just the query to the database.

From the documentation of the Local property:

Gets an ObservableCollection that represents a local view of all Added, Unchanged, and Modified entities in this set. This local view will stay in sync as entities are added or removed from the context. Likewise, entities added to or removed from the local view will automatically be added to or removed from the context.

So if you want to access the elements, always use the Local property to do it.

Comments