0

I have an "Investment" entity that is derived from "BaseEntity". If I create and add a new "Investment" like so:

investment = new Investment();
investment.Name = "Investment 01";
_context.BaseEntities.AddObject(entity);

and query the count (before saving changes)

_context.BaseEntities.OfType<Investment>().Count();

it returns zero. The same line returns 1 after _context.SaveChanges();

What am I doing wrong?

Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
SolarX
  • 1,873
  • 2
  • 18
  • 26

3 Answers3

2

You are not doing anything wrong. This is how EF works. No changes are done in database until you execute SaveChanges - it is called unit of work. You prepare all changes in memory and then save them all together in one transaction.

Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
  • I now that. But my understanding is, that the DataContext should give me the right Count because it has new newly added object in memory. If I do: _container.BaseEntities.Count() I get the right number. – SolarX Apr 19 '11 at 11:22
  • I would like to have an ObjectSet of "Investment" rather than an "ObjectQuery". – SolarX Apr 19 '11 at 11:24
0

An entity which is still in insert state will not be included in query results since the object has not been persisted with the SaveChanges()

Executing the _context.BaseEntities.OfType<Investment>().Count(); method will make a request to the SQL server and return the results found in the database.

When using the GetObjectByKey method, a way to fetch the entity from the context instance if it was previously loaded,which is found on the ObjectContext, will also react the same way. Since the object is in new / insert state, the context will treat it as non existant until the save.

Edit:

In the code in the question you are using _context and in the comment you are mentioning _container.BaseEntities.Count()

what is the difference between these two objects ?

Alexandre Brisebois
  • 6,599
  • 12
  • 50
  • 69
0

This is correct behavior as the object is sitting in the state manager until you call SaveChanges(). Only after you call SaveChanges() will the object become available in your count.

Craig
  • 6,869
  • 3
  • 32
  • 52