【问题标题】:What happens to my DbContext after I run a stored procedure that modifies my entities?运行修改实体的存储过程后,我的 DbContext 会发生什么情况?
【发布时间】:2014-03-08 06:14:14
【问题描述】:

场景: 我有一个自定义DbContext。我正在使用底层ObjectContextStoreConnection 属性来运行修改多个实体的存储过程(在我的自定义DbContext 中有一个DbSet)。我的 DbContext 和存储库由 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 过时的风险,如果是这样,我如何让它成为当前的,而不是处理它并创建一个新的?

【问题讨论】:

    标签: c# entity-framework stored-procedures dbcontext entity-framework-6


    【解决方案1】:

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

    你可以试试这样的:

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

    【讨论】:

      猜你喜欢
      • 2023-04-04
      • 2011-02-13
      • 1970-01-01
      • 2011-03-25
      • 1970-01-01
      • 2021-06-02
      • 2015-12-04
      • 2017-07-18
      相关资源
      最近更新 更多