0

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?

igorGIS
  • 1,888
  • 4
  • 27
  • 41

2 Answers2

1

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 

msdn ref

Ric
  • 12,855
  • 3
  • 30
  • 36
0

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

igorGIS
  • 1,888
  • 4
  • 27
  • 41
  • 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? – Ric Jan 14 '13 at 16:24
  • 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 Jan 14 '13 at 16:33
  • Probably i need to change logic, make validation before adding object and then savе it – igorGIS Jan 14 '13 at 16:38
  • 1
    And here is same problem and solution: http://stackoverflow.com/questions/6990618/querying-objects-after-addobject-before-savechanges – igorGIS Jan 14 '13 at 16:45
  • 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. – Ric Jan 14 '13 at 20:46