我想更新一些实体而不先将它们加载到内存中。我知道这应该有效:
var myEntity = new MyEntity
{
PkId = 123
};
myContext.Entry(myEntity).State = EntityState.Modified;
myEntity.ProcessTime = DateTime.Now;
myContext.SaveChanges();
但在致电SaveChanges
时,我面临一些DbEntityValidationException
,说明需要一些字段。我使用EF4(ObjectContext
),但这从未发生过。此外,它只说明了3个必填字段,尽管有8个以上的必填字段。
在SaveChanges
之前尝试过这个问题(没有运气):
myContext.Entry(myEntity).Property(e=>e.ProcessTime).IsModified = true;
如果我使用_context.Configuration.ValidateOnSaveEnabled = false;
,则SaveChanges
不会抛出异常,但会更糟;它使用默认的clr值更新db-row!
我该怎么做?
我正在使用:
答案 0 :(得分:0)
最后,我发现这种令人厌恶(和错误)的方式有效:
var myEntity = new MyEntity
{
PkId = 123
};
// If you skip this, the validation error occurs again.
// If you keep it, you might be killed.
myContext.Configuration.ValidateOnSaveEnabled = false;
var dbEntry = myContext.Entry(myEntity);
// Let it think everything is just fine.
dbEntry.State = EntityState.UnChanged;
// If you have some fields already having updated value (before attaching),
// Inform it that it has been modified
// dbEntry.Property(r => r.YourProperty).IsModified = true;
// Change your field value.
// If you change a field, the state is already modified
// So, you don't need to tell it. Just change.
myEntity.ProcessTime = DateTime.Now;
// Call to save it and hope you did not forget to init any field value of any
// entity to be inserted in this context. If you did (mistakenly), it will remain
// silent and kill you later
myContext.SaveChanges();