dar25
dar25

Reputation: 93

Entity Framework DbSet not reflecting latest changes to underlying data

What are the possible reasons for a query on a System.Data.Entity.DbSet not reflecting the latest changes to the underlying data? I have the following code, within an Asp.Net MVC project:

    ShoppingEntities dbcontext = new ShoppingEntities();

    var cartID = 200;
    Cart check = dbcontext.Cart.Find(cartID);

    //here check.quantity equals 9, and the back-end database table shows quantity = 9;

    myServiceController.CallSP_UpdateCart(cartID); //back-end stored procedure sets quantity = 10

    check = dbcontext.Cart.Find(cartID);

    // here check.quantity still equals 9, but the back-end database table shows quantity = 10;

In the code comments, when I say "back-end database table shows quantity = xx", i am referring to a SQL query i do direclty on the database with Sql Server Management Studio. I have to use Stored procedure to update the backend data because there is a lot of complex business logic there and not practical to use EF.

Thanks in advance for any help.

Upvotes: 3

Views: 3356

Answers (1)

Ran Turner
Ran Turner

Reputation: 18026

Find will make a round-trip to the DB only if the entity with the given key is not found in the context.

If an entity with the given primary key values is being tracked by the context (like in your case), then it is returned immediately without making a request to the database.

If the entity does not exist within the context, a query is being made to the DB for an entity with the given primary key values and this entity is attached to the context and returned (Null is returned if not entity is not found).

To get the refresh data it is better to dispose the DbContext instance after each request.

What You can also do it to reload the entity and get it's updated values from the DB.

Context.Entry<T>(entity).Reload()

Upvotes: 7

Related Questions