2011-04-26 75 views
4

我正在開發具有自我跟蹤實體的WCF數據服務,並且希望防止客戶端插入重複的內容。無論何時POST數據沒有提供數據鍵的值,我都必須執行一些邏輯來確定數據是否已經存在於我的數據庫中。我寫了一個像這樣的更改攔截:WCF數據服務 - 更新記錄而不是插入它

[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被忽略,因此記錄總是被插入,從不更新。它甚至有可能做到嗎?提前致謝。

回答

2

Hooray!我設法做到了。

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

我不得不改變其他地方的對象狀態,即。通過調用ObjectStateManager的.ChangeObjectState,它是底層EntityContext的一個屬性。我被.MarkAsModified()方法誤導了,在這一點上,我不確定它的作用。