Get added entities in the query

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?


For example,


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>()

This entry was posted in 7671, 7674. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>