WCF数据服务 - 更新记录而不是插入记录

时间:2011-04-26 16:41:38

标签: wcf entity-framework odata wcf-data-services

我正在使用自我跟踪实体开发WCF数据服务,我想阻止客户端插入重复的内容。每当他们POST数据而不提供数据键的值时,我必须执行一些逻辑来确定数据是否已存在于我的数据库中。我写了一个像这样的Change拦截器:

[ChangeInterceptor("MyEntity")]
public void OnChangeEntity(MyEntity item, UpdateOperations operations){
  if (operations == UpdateOperations.Add)
  {
    // Here I search the database to see if a matching record exists.
    // If a record is found, I'd like to use its ID and basically change an insertion
    // into an update.
    item.EntityID = existingEntityID;
    item.MarkAsModified();
  }
}

但是,这不起作用。忽略existingEntityID,因此始终插入记录,从不更新记录。它甚至可以吗?提前谢谢。

1 个答案:

答案 0 :(得分:2)

万岁!我设法做到了。

item.EntityID = existingEntityID;
this.CurrentDataSource.ObjectStateManager.ChangeObjectState(item, EntityState.Modified);

我不得不在其他地方更改对象状态,即。通过调用ObjectStateManager的.ChangeObjectState,它是底层EntityContext的一个属性。我被.MarkAsModified()方法误导了,在这一点上,我不确定它是做什么的。