I've entity type called 'Question', when i create new instance of it and add it to entity set 'Questions' (using AddObject()), than call SaveChanges() method on context, all works fine. But when i added it, but not call SaveChanges() yet and try to execute some linq against 'Questions' the query result not contain recently added 'Question' object, it seems invisible for linq until SaveChanges() is called. This is a correct behavior or i miss something?
-
Is your LINQ query working on the same instance of the ObjectContext as the code that added the object.Daniel Hilgarth– Daniel Hilgarth2013-01-14 16:08:25 +00:00Commented Jan 14, 2013 at 16:08
-
Thank for reply Daniel. The context instance the same.igorGIS– igorGIS2013-01-14 16:14:32 +00:00Commented Jan 14, 2013 at 16:14
Add a comment
|
2 Answers
I believe this is correct behaviour, especially if you are referring to Entity Framework.
This should be able to get objects that you have added before save changes is called ie once you have added them:
ObjectStateManager.GetObjectStateEntries
Comments
For simplicity i decide not to use LINQ but use Count() method to see how many question objects i have after AddObject()
(_context.Questions.ToArray()).Count()
got 8
// defaultQuestion object initialization here ...
_context.Questions.AddObject(defaultQuestion);
(_context.Questions.ToArray()).Count()
again got 8
5 Comments
Ric
if you got 8 items on the first count and 8 again on the second count after adding a new object, shouldn't there be 9 objects?
igorGIS
I expect 9 items too, but it is 8 :) Thank for the link indeed there is ObjectStateManager.GetObjectStateEntries() method when executed i can see my object in its result, but it is not what i want. Why i need to AddObject and then SaveChanges later that i want some validation on that object before push it to source.
igorGIS
Probably i need to change logic, make validation before adding object and then savе it
igorGIS
And here is same problem and solution: stackoverflow.com/questions/6990618/…
Ric
the point is to use the ObjectStateEntry object before changes are persisted to the database. once save changes is called, an event is raised in which validation can be done on each entry and on each "state" so that changes can be rejected before they are in the DB.