运行修改实体的存储过程后,我的 DbContext 会发生什么情况



场景:我有一个自定义DbContext.我正在使用基础ObjectContextStoreConnection 属性来运行一个存储过程,该过程修改多个实体(在我的自定义DbContext中具有DbSet)。我的数据库上下文和存储库由 Unity v3 提供。

示例

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

问题:在此存储过程之后,我是否冒着过时DbContext的风险,如果是这样,如何让它成为当前存储过程,而不是释放它并创建一个新存储过程?

如果在运行存储的过程后继续使用它,则此时 DbContext 将过时。根据此答案(https://stackoverflow.com/a/18830466/3294324),您可以在不创建新上下文的情况下更新上下文。

你可以尝试这样的事情:

var Context = ((IObjectContextAdapter)_ctx).ObjectContext;
Context.Refresh(RefreshMode.StoreWins, Context.ObjectStateManager.GetObjectStateEntries());

相关内容

最新更新