如何在不提供所有字段的情况下更新分离的实体?

时间:2015-10-18 09:12:55

标签: entity-framework entity-framework-6

我想更新一些实体而不先将它们加载到内存中。我知道这应该有效:

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!

我该怎么做?

我正在使用:

  • EF 6.1.3(数据库优先)
  • Oracle Data Provider NET 12c第4版
  • Visual Studio 2012
  • Windows 7 x64

1 个答案:

答案 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();
相关问题