Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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                         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?

like image 672
e-mre Avatar asked Jun 21 '11 13:06

e-mre


People also ask

What is persistence in Entity Framework?

Entity persistence is the process that stores entities data inside the database. Triggering this procedure is simple as invoking the SaveChanges method of the ObjectContext class (which is the class from which the OrderITEntities class in OrderIT inherits).

How do I save changes in Entity Framework?

Entity Framework Core Save Changes to the database using the SaveChanges method of DbContext. When we use the SaveChanges it prepares the corresponding insert , update , delete queries. It then wraps them in a Transaction and sends them to the database. If any of the queries fails all the statements are rolled back.

How do I save a record in Entity Framework?

Insert Data Add methods add a new entity to a context (instance of DbContext) which will insert a new record in the database when you call the SaveChanges() method. In the above example, context. Students. Add(std) adds a newly created instance of the Student entity to a context with Added EntityState.

Where is AsNoTracking used?

The AsNoTracking method can save both execution times and memory usage. Applying this option really becomes important when we retrieve a large amount of data from the database.


1 Answers

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>() 
like image 155
Craig Stuntz Avatar answered Oct 11 '22 14:10

Craig Stuntz