为什么Entity Framework查询不返回未保存的实体 [英] Why do Entity Framework queries not return unsaved entities

查看:141
本文介绍了为什么Entity Framework查询不返回未保存的实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

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);

请注意, Products_Again 被查询而不保存

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

Products_Again 包含与 Products_First 相同数量的产品。为什么是这样?新的产品由相同的上下文对象添加和跟踪。为什么我不能在新的查询结果中看到新产品?

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?

在上下文中添加新对象后,是否有一种方法来达到新对象而不保存更改? / p>

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

推荐答案

类型 ObjectQuery< T> 的属性,如 myContext.Product 始终查询数据库。这就是他们所做的。

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

在EF 4.1中,您可以使用 DbSet< T> .Local 来查询内存。

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

在EF< 4.1你将使用:

In EF < 4.1 you would use:

ObjectContext.ObjectStateManager.GetObjectStateEntries(EntityState.Added).Select(o => o.Entity).OfType<Product>()

这篇关于为什么Entity Framework查询不返回未保存的实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆