2016-09-15 52 views
1

我正在與ArangoDatabase及其驅動程序CRUD功能的小應用程序:ArangoDb.Net UPSERT總是插入

http://www.arangoclient.net/

這裏是我的代碼:

 var insert = new Account 
     { 
      Email = "[email protected]", 
      FirstName = "Adam", 
      LastName = "Smith" 
     }; 

     var update = new Account 
     { 
      Email = "[email protected]", 
      FirstName = "John", 
      LastName = "Peterson" 
     }; 

     using (var arangoDatabase = new ArangoDatabase(new DatabaseSharedSetting() 
     { 
      Url = "http://127.0.0.1:8529/", 
      Database = "_system", 
      Credential = new NetworkCredential() 
      { 
       UserName = "root", 
       Password = "xvxvc" 
      } 
     })) 
     { 
      arangoDatabase.Query() 
       .Upsert(_ => new Account() {Email = insert.Email}, 
        _ => insert, ((aql, x) => update)) 
        .In<Account>() 
        .Execute(); 
     } 

第一次運行時,[插入]對象被添加到數據庫中。 因此,我的數據庫現在是:

Data has been imported successfully

但在運行代碼的第二次,它會引發我一個錯誤:

unique constraint violated (while executing). ErrorNumber: 1210 HttpStatusCode: 409 

的問題是:什麼是我的問題,以及如何解決這個問題?

謝謝

enter image description here

回答

2

問題可能是UPSERT搜索表達式系列化:

假設Account類的定義是:

public class Account 
{ 
    public string Email { get; set; } 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
} 

UPSERT搜索表達式:new Account() {Email = insert.Email}意志連載到:

{ Email: "[email protected]", FirstName: null, LastName: null }

但什麼期望是:

{ Email: "[email protected]" }

由於搜索表達式從來沒有發現一個文檔,然後插入會發生,你會得到unique constraint violated

有兩種解決方案,以避免序列化FirstNameLastName成員:

一個是我們可以使用Json.net JsonProperty屬性忽略序列化的空值:

public class Account 
{ 
    public string Email { get; set; } 
    [Newtonsoft.Json.JsonProperty(NullValueHandling = NullValueHandling.Ignore)] 
    public string FirstName { get; set; } 
    [Newtonsoft.Json.JsonProperty(NullValueHandling = NullValueHandling.Ignore)] 
    public string LastName { get; set; } 
} 

而另一種方法是使用搜索表達式的匿名對象:

arangoDatabase.Query() 
       .Upsert(_ => new Account() {Email = insert.Email} 

// should be 

arangoDatabase.Query() 
       .Upsert(_ => new {Email = insert.Email} 

關於使用匿名對象CT是Email成員能夠解決到別的東西的基礎上您指定的內容爲它命名規則,例如:

public class Account 
{ 
    [DocumentProperty(Identifier = IdentifierType.Key)] 
    public string Email { get; set; } 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
} 

如果指定Email作爲密鑰標識符,那麼你應該在匿名對象使用_key

arangoDatabase.Query() .Upsert(_ => new { _key = insert.Email }