开发者

Why do Entity Framework queries not return unsaved entities

开发者 https://www.devze.com 2023-03-14 05:02 出处:网络
Consider the following code: var Products_First = (from Entities.Product p in myContext.Product select p);

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

精彩评论

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

关注公众号