为什么Entity Framework查询不返回未保存的实体 [英] Why do Entity Framework queries not return unsaved entities
问题描述
考虑以下代码:
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屋!