在SaveChanges()上将集合项的属性覆盖回旧数据

时间:2018-03-29 12:54:14

标签: c# entity-framework entity-framework-6 change-tracking

我目前正在使用基于模型设计器的代码优先设计开发MVVM应用程序。到目前为止,我已经能够将所有基本的CRUD操作都用于单个实体,但是我似乎无法使用SaveChanges()来改变集合对象的属性 - 我已经使用了一个SQL分析器来查看它是否尝试使用旧值进行更新,并在SaveChanges()我的更改恢复为旧值后立即执行步骤!

其他一些信息:

  • 我的dbContext使用来自PRISM / Unity的DI加载,并作为工作单元保存为"详细信息"用户将编辑然后保存的页面。
  • 我的WPF UI绑定正确,可以修改对象级别的更改。
  • 我可以成功使用Add()插入实体。
  • 我已经验证了子集合中实体的实体状态是通过设置和简化调试来修改。
  • 我尝试在任何或所有项目上手动Attach()AddOrUpdate()
  • 我已关闭所有Lazy Loading,而是手动包含所有馆藏。
  • 我已手动将Entry()和CurrentValue的IsModified属性设置为所需的设置。
  • 我尝试将我的VM属性绑定到他们的数据 dbContext.Classes.Local.ToBindingList()new ObservableCollection<Class>(Entity.Property)

我可以在这里找到什么吗?这是我尝试过的一次尝试:     //分配包含关系的Index对象     Index = await _model.PersonIndexes.Include(i =&gt; i.PersonAddresses).FirstAsync(i =&gt; i.Id == IndexId);

// Grabbing a filtered set of Addresses based on their data
var query = Index.PersonAddresses.Where(e => e.Condition == true );
Addresses = new ObservableCollection<PersonAddress>(await query.ToListAsync());

// Ensure state is tracked (I've tried with and without all  combinations of these)
foreach (PersonAddress addr in Addresses)
{
     //_model.PersonAddresses.AddOrUpdate(a => a.Id, addr);
     if (addr.PendingRemoval)
     {
           _model.PersonAddresses.Attach(addr);
           _model.Entry(addr).Property(a => a.PendingRemoval).CurrentValue = true;
           _model.Entry(addr).Property(a => a.PendingRemoval).IsModified = true;
      }
}

// Saving (after this line the properties of the entities in the related collection get reverted to their old values - i.e. if I change a phone number in the UI, the save below will replace the new values with the previous number.
await _model.SaveChangesAsync();

1 个答案:

答案 0 :(得分:0)

所以事实证明,这是一个令人遗憾的配置错误,也是一个糟糕的巧合:

1)检查模型和服务器架构以确保它们处于同步状态(特别是如果使用EF生成的代码)。在我的情况下,他们不是,这导致......

2)SaveChanges()覆盖了我的相关资源,因为我没有注意到他们被错误地设置为在我的模型代码中将StoredGeneratorPattern设置为Computed。这导致更改的值被忽略和覆盖。

3)围绕此问题的测试用例只实现了标记错误的相同属性,使显示所有更改都被还原 - 导致问题代码实际位置混淆。如果另一列已被修改并与其他列一起观看,则可能很快就会发现。