我在 Visual Studio 2008 中使用 Entity Framework ,当然 .NET Framework 和 VS 本身都是 SP1。我的应用程序是在n层环境中开发的。第一步,我将数据从上下文转换为集合并序列化给用户。
HRMSDBContext context = new HRMSDBContext();
List<InHouseTrainingHead> heads = context.InHouseTrainingHead.ToList<InHouseTrainingHead>();
foreach (InHouseTrainingHead head in heads)
{
context.Detach(head);
}
return heads;
用户更改一些数据并单击“保存”后,此列表将返回到保存方法。
HRMSDBContext context = new HRMSDBContext();
foreach (InHouseTrainingHead head in lists)
{
context.Attach(head);
context.ApplyPropertyChanges(head.EntityKey.EntitySetName, head);
}
context.SaveChanges();
不幸的是,在 SaveChanges() 之后没有任何反应。我该如何解决这个问题?
最佳答案
扩展 Daniel Brückner 的答案 - 您的示例中发生的情况是您尝试在 head
对象与其自身之间进行 ApplyPropertyChanges
。显然,没有发生任何变化,因此没有保存任何内容。但是,如果您不想从数据库中获取记录,则可以手动将新附加实体的 EntityState
设置为 Modified
。在这种情况下,它将保存在数据库中:
HRMSDBContext context = new HRMSDBContext();
foreach (InHouseTrainingHead head in lists)
{
context.Attach(head);
ObjectStateEntry addedEntity = context.ObjectStateManager.GetEntry(head);
addedEntity.ChangeState(EntityState.Modified);
}
context.SaveChanges();
关于entity-framework - Entity Framework SaveChanges() 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3236254/