In EntityFramework, is that possible to query the objects that have just been added to the context using AddObject but before calling the SaveChanges method?
Thanks
In EntityFramework, is that possible to query the objects that have just been added to the context using AddObject but before calling the SaveChanges method?
Thanks
To persist an entity you usually add it to it's
DbSet
in the context.For example
Surprisingly, querying
context.Bars
, the just added entity cannot be foundAfter
context.SaveChanges()
the same line will result1
The
DbSet
seems unaware to changes until they're persisted on db.Fortunately, each
DbSet
has aLocal
property that acts like theDbSet
itself, but it reflect all in-memory operationsYou can also use
Local
to add entitiesand get rid of the weird behavior of Entity Framework.
In hibernate transient instances are already attached to context. Just stumbled upon this EF restriction.
I did not managed to intersect/union the
ObjectSet
with its transient entitiesObjectSet.Local
but for our usecase the below find method is sufficient.In our cases we create some entities lazy depending on unique criteria during an iteration
Find method
If you are using an repository pattern you can create a method like:
you can query objects like this,
this will query the objects which are in added state. If you want other states too you can pass all other states to
GetObjectStateEntries
method like this.