开发者

Why do Entity Framework queries not return unsaved entities

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  
            开发者_如何学JAVA          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?


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>()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜