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?
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());