【发布时间】:2012-08-31 01:50:38
【问题描述】:
如果实体在 DbContext 之外更改(是一个分离的实体),我在更新实体时会遇到一个小问题。如果我附加修改后的实体,它的状态不会被修改。
我的代码如下所示:
var specificationToSave = GetSpecificationFromTmpStore(userSessionGuid);
using (var context = DataContextFactory.GetDataContext())
{
// this works for update, if I change the values inside the context while debugging
// but it breaks with new entities
context.Specifications.Attach(specificationToSave);
// this works for insert new entities, modified entities will be saved as new entities
context.Specifications.Add((specificationToSave);)
context.SaveChanges();
}
我知道 NHibernate 和它的方法 SaveOrUpdate。 NHibernate 根据值决定它是更新还是插入实体。
使用 EF 4.x 和在 DbContext 之外修改的实体执行此操作的最佳做法是什么? 如何告诉 EF 该实体处于修改状态?
【问题讨论】:
标签: c# entity-framework entity-framework-4 code-first