37

Consider the following code:

var Products_First = (from Entities.Product p in myContext.Product  
                      select p);

Entities.Product newProduct = new Entities.Product();
newProduct.Name = "New Product";
myContext.Products.AddObject(newProduct);

var Products_Again = (from Entities.Product p in myContext.Product  
                      select p);

Notice here that Products_Again is queried without saving the context, that is myContext.SaveChanges() is not called.

Products_Again contains the same number of products as Products_First. Why is this? A new Product is added and tracked by the same context object. Why can not I see the new product in the new query results?

After adding new object to the context is there a way to reach the new object without saving changes?

Chris
  • 44,602
  • 16
  • 137
  • 156
e-mre
  • 3,305
  • 3
  • 30
  • 46

1 Answers1

38

Properties of type ObjectQuery<T>, like myContext.Product, always query the DB. That's what they do.

In EF 4.1 you can use DbSet<T>.Local to query memory.

In EF < 4.1 you would use:

ObjectContext.ObjectStateManager.GetObjectStateEntries(EntityState.Added).Select(o => o.Entity).OfType<Product>()
Matt
  • 74,352
  • 26
  • 153
  • 180
Craig Stuntz
  • 125,891
  • 12
  • 252
  • 273
  • So, to get a results set with elements from both DB and memory I should keep a separate list of my own and try to keep it up to date. Is is the proposed solution for EF 4.0? – e-mre Jun 22 '11 at 05:31
  • I don't understand your question -- I gave you a solution for EF 4.0 / EF 1. – Craig Stuntz Jun 22 '11 at 13:27
  • 3
    It worked, but the <4.1 solution should include `Select(o=>o.Entity)`: `ObjectContext.ObjectStateManager.GetObjectStateEntries(EntityState.Added).Select(o=>o.Entity).OfType()` – surfen Jan 27 '12 at 20:15