C# 运行修改实体的存储过程后,DbContext会发生什么变化?
场景: 我有一个自定义的C# 运行修改实体的存储过程后,DbContext会发生什么变化?,c#,entity-framework,stored-procedures,dbcontext,entity-framework-6,C#,Entity Framework,Stored Procedures,Dbcontext,Entity Framework 6,场景: 我有一个自定义的DbContext。我正在使用底层ObjectContext的StoreConnection属性来运行一个存储过程,该存储过程修改多个实体(在我的自定义DbContext中有一个DbSet)。My DbContext和存储库由Unity v3提供 示例: private MyContext _ctx; private IGenericRepository<Foo>(); private IGenericRepository<Bar>(); pub
DbContext
。我正在使用底层ObjectContext
的StoreConnection
属性来运行一个存储过程,该存储过程修改多个实体(在我的自定义DbContext
中有一个DbSet
)。My 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>?
}
private MyContext\u ctx;
私有IGenericRepository();
私有IGenericRepository();
公共无效DoSomethingFooAndBar()
{
var connection=\u ctx.StoreConnection;//在我的自定义上下文中公开ObjectContext.StoreConnection
使用(var cmd=connection.CreateCommand())
{
command.CommandText=“dbo.ModifyFooAndBar”;
command.CommandType=CommandType.storedProcess;
command.ExecuteNonQuery();
}
//我的DbSet和DbSet的状态是什么?
}
问题:
在这个存储过程之后,我是否会有一个过时的
DbContext
的风险?如果是这样,我如何使它变得最新,而不处理它并创建一个新的呢?如果在运行存储过程之后继续使用它,DbContext此时将过时。根据这个答案(),您可以在不创建新上下文的情况下更新上下文
您可以尝试以下方法:
var Context = ((IObjectContextAdapter)_ctx).ObjectContext;
Context.Refresh(RefreshMode.StoreWins, Context.ObjectStateManager.GetObjectStateEntries());