I had the following question:
Why, when we add an entity in an ObjectContext, don’t we get it from a query until we save the ObjectContext?
context.MyEntities.Count returns n.
Now, if we add a new entity in the context, context.MyEntities.Count still returns n, not n + 1.
In fact, when we execute a query, the query is translated into a sql query and so, the result is the result of the database and until you call the SaveChanges method on the context, the Added or Deleted entities are ignored.
So how to consider the EntityState?
We can use the ObjectStateManager.
You have to load all the entities you need from the DB to have them in the ObjectContext’s ObjectStateManager.
Then, you can get the entities with:
context.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified | EntityState.Unchanged).Select(e => e.Entity).OfType<MyEntityType>()