2

I am using SimpletInjector to inject the entity framework context in controller using following code:

    private static void Initializer(Container container)
    {
        container.RegisterSingle<IDbContext,  SpotterContext>();
        container.RegisterSingle<IUnitOfWork, UnitOfWork>();
    }

I am using the injected context to execute stored procedure which will have only UPDATE or DELETE statements using the following code:

context.Database.ExecuteSqlCommand(<spname>, <params array>);         

The problem I am facing is that the changes made by the stored procedure in database are not getting reflected in the context and when accessing the updated data using the context, I am getting the old data and not the updated data.

How to update the context after executing a stored procedure to get latest data from database?

  • 1
    Read [this](http://stackoverflow.com/a/10588594/1515209) - you shouldn't really register the context as a singleton. – qujck Oct 17 '14 at 12:19
  • Do note that @qujck is spot on and your problems are caused by using the dbcontext as singleton. Using the Reload method might look like it solves your problem, but as qujck's link explains, a dbcontext can't be used across threads and requests. – Steven Oct 19 '14 at 14:52

1 Answers1

1

Had to solve exactly the same problem recently. As it appears, Reload() method of context' Entry member works just fine.

Sorry, I don't know C#, so can't post a code sample on that language. In VB.NET it looks like this:

Dim CurClient As Client = Ctx.Clients.Where(Function(cl) cl.Id = ClientId).First()

Ctx.Entry(Of Client)(CurClient).Reload()

Here, Ctx is an EF context.

The only thing I haven't tested yet is whether this method also reloads records from child tables, if they exist.

Roger Wolf
  • 7,307
  • 2
  • 24
  • 33
  • I really appreciate the answer that you gave, but I have a query regarding it. Will 'Reload' calling collapses the existing entity states set by other user and loads the data from db? Eg: User 1 has set one entity state to 'modified', and then user 2 came in and executed the stored procedure and called 'Reload', then will the user 1 entity state remains uneffected after 'Reload' or those changes will be lost. – Manikandhar Oct 17 '14 at 15:08
  • @Manikandhar, it depends on how many contexts you have. If those users each has a personal context, then changes made by User1 in his personal context will remain unaffected. If several users share the same EF context, then yes, User1 changes will be lost. – Roger Wolf Oct 18 '14 at 04:12
  • Thanks a lot Roger, the solution you pointed worked out for me. Thanks a lot again...! – Manikandhar Oct 20 '14 at 04:49
  • 1
    The Reload method for the context entry does not refresh the child objects when parent object is refreshed. It refreshes the data of one particular row form respective database table. – Manikandhar Nov 21 '14 at 06:32