DbSet: missing added item

In the DbSetEntity Framework Entity Collection (6.1.3), when I add a new element, it is not subsequently returned from the collection. This is strange and unexpected. Here are some sample code:

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

How can it be? When I query dbContext.Entitiesin the immediate Visual Studio window, it says something like "Local: Count = 4". Why is he hiding a new element from me?

Update: If this collection does not do the obvious thing - returning what has been added before - what should I do instead? It should return all records from the database on the first call, and it should also include all changes (add and delete) on the call later. SaveChangesonly called when the user has finished editing. Before that, you need a collection! SaveChangescan also be called somewhere in the middle when the user finishes editing, but the code can return and the view will be displayed again at a later time.

+4
source share
4 answers

A DbSet Local. ObservableCollection, . DbSet .

Local:

ObservableCollection, , . , . , , , .

, , Local .

+4

, dbContext, Use dbContext.SaveChanges(); dbContext.EntityState.Added

+2

You must save the changes. Try

dbContext.State = EntityState.Added;
dbContext.SaveChanges();
0
source

you can use the following code to get all the elements

foreach (var track in dbContext.ChangeTracker.Entries())
{
     if (track.State == EntityState.Deleted)
         Entity s = (Entity)track.OriginalValues.ToObject();
     else
         Entity s = (Entity)track.CurrentValues.ToObject();
}
0
source

Source: https://habr.com/ru/post/1608974/


All Articles