What happens to my DbContext after I run a stored procedure that modifies my entities?

c# dbcontext entity-framework entity-framework-6 stored-procedures

Question

Scenario: I have a custom DbContext. I am using the StoreConnection property of the underlying ObjectContext to run a stored procedure that modifies several entities (which have a DbSet in my custom DbContext). My DbContext and Repositories are supplied by Unity v3.

Example:

private MyContext _ctx;
private IGenericRepository<Foo>();
private IGenericRepository<Bar>();

public void DoSomethingFooAndBar()
{
    var connection = _ctx.StoreConnection; //Exposed ObjectContext.StoreConnection in my custom context
    using (var cmd = connection.CreateCommand())
    {
        command.CommandText = "dbo.ModifyFooAndBar";
        command.CommandType = CommandType.StoredProcedure;
        command.ExecuteNonQuery();
    }
    //What is the state of my DbSet<Foo> and DbSet<Bar>?
}

Question: Do I run the risk of having a stale DbContext after this stored procedure and, if so, how do I get it to become current short of disposing of it and creating a new one?

1
3
2/10/2014 6:37:40 PM

Accepted Answer

The DbContext will be stale at this point, if you continue to use it after running the stored proc. According to this answer (https://stackoverflow.com/a/18830466/3294324) you may be able to update your context without creating a new one.

You could try something like this:

var Context = ((IObjectContextAdapter)_ctx).ObjectContext;
Context.Refresh(RefreshMode.StoreWins, Context.ObjectStateManager.GetObjectStateEntries());
2
5/23/2017 12:20:40 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow