Why do Entity Framework queries not return unsaved

2019-01-18 01:45发布

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?

1条回答
对你真心纯属浪费
2楼-- · 2019-01-18 02:10

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>()
查看更多
登录 后发表回答