实体框架:部分更新记录不起作用

问题描述 投票:0回答:1

我有以下设置:

enter image description here注入所有实例,UnitOfWork和DataContext是单例。

我想对记录进行部分更新。在通用存储库中,我在更新语句中有以下代码:

dbSet.Attach(entity);
if (updatedProperties != null)
{
   foreach (var property in updatedProperties)
   {
      unitOfWork.DataContext.Entry<TEntity>(entity).Property(property).IsModified = true;
   }
}

在我的更新方法中,我接受带有更新字段的字符串列表。

使用以下代码从usermanager调用此方法:

userRepo.Update(origUser, updatedProperties);
if(processToDB)
{
    unitOfWork.SaveChanges();
}

变量processToDB设置为true。我进入代码,我在changetracker中看到实体在那里,但更新永远不会发生。

那么,是什么解决了这个问题,但是我没有发现这是一个很好的解决方案,直接从通用存储库中的Update方法调用SaveChanges方法:

dbSet.Attach(entity);
if (updatedProperties != null)
{
   foreach (var property in updatedProperties)
   {
      unitOfWork.DataContext.Entry<TEntity>(entity).Property(property).IsModified = true;
   }
   unitOfWork.SaveChanges(); //added
}

为什么在用户管理器上调用savechanges时它不起作用,它毕竟是相同的unitOfWork和DataContext(因为它们是单例)。

entity-framework repository unit-of-work
1个回答
0
投票

您不需要为每个实体属性设置IsModified。使用AutoDetectChangesEnabled属性并设置为true,同时将EF模型初始化为

DbContext.Configuration.AutoDetectChangesEnabled = true;

它将使EF跟踪实体对象的变化。您可以使用unitOfWork.DataContext(entity).State == EntityState.Modifed进行检查。

如果满足上述条件,则更新您的实体。

© www.soinside.com 2019 - 2024. All rights reserved.