当前位置 : 主页 > 编程语言 > c语言 >

c# – 如何刷新DbContext

来源:互联网 收集:自由互联 发布时间:2021-06-25
我想刷新我的DbContext的所有实体而不重新创建它,我尝试了以下内容,但没有一个是有意义的: var context = ((IObjectContextAdapter)myDbContext).ObjectContext;var refreshableObjects = (from entry in context.Obje
我想刷新我的DbContext的所有实体而不重新创建它,我尝试了以下内容,但没有一个是有意义的:

var context = ((IObjectContextAdapter)myDbContext).ObjectContext;

var refreshableObjects = (from entry in context.ObjectStateManager.GetObjectStateEntries(
                                   EntityState.Added
                                   | EntityState.Deleted
                                   | EntityState.Modified
                                   | EntityState.Unchanged)
                          where entry.EntityKey != null
                          select entry.Entity);

context.Refresh(RefreshMode.StoreWins, refreshableObjects);
//.......................................................................
foreach (var entry in this.Orm.ChangeTracker.Entries())
{
    entry.State = EntityState.Unchanged;
}
this.Orm.ChangeTracker.DetectChanges();

并且唯一一个刷新我的DbContext:

foreach (var i in this.Orm.ChangeTracker.Entries())
    i.Reload();

但它太慢了.你能帮我选择正确的方法吗?

我刚刚发现应该评估Enumerable结果,因为Refresh方法将其作为对象获取并且不对其进行评估.

var context = ((IObjectContextAdapter)myDbContext).ObjectContext;
var refreshableObjects = (from entry in context.ObjectStateManager.GetObjectStateEntries(
                                           EntityState.Added
                                           | EntityState.Deleted
                                           | EntityState.Modified
                                           | EntityState.Unchanged)
                          where entry.EntityKey != null
                          select entry.Entity).ToList();

context.Refresh(RefreshMode.StoreWins, refreshableObjects);

我更喜欢以下内容:

var refreshableObjects = myDbContext.ChangeTracker.Entries().Select(c=>c.Entity).ToList();
context.Refresh(RefreshMode.StoreWins, refreshableObjects);
网友评论