2016-03-09 32 views
0

我正在研究一個庫應用程序,或者說需要連接到Azure DocumentDB。在我的DocumentDB中,我有一個DocumentCollection,它是BookCollection和一個Document - BookDocument。每次將新書添加到系統中時,都必須使用新的Book對象更新此文檔,我的問題是:我該怎麼做?到目前爲止,我有這樣的:使用Azure DocumentDB並將對象添加到文檔

public static async Task AddBook(Book newBook) 
{ 
using (_client = new DocumentClient(new Uri(_endPointURL),_authKey))    
{ 

      Database database = (from db in _client.CreateDatabaseQuery() 
       where db.Id == "BookAssignment" 
       select db).AsEnumerable().FirstOrDefault(); 
      Console.WriteLine("Connected to Database: " + database.Id); 
      //Create collection 
      string dbCollectionBooks = "Books"; 
      DocumentCollection dbCollection = 
       (from collections in _client.CreateDocumentCollectionQuery(database.SelfLink) 
        where collections.Id == dbCollectionBooks 
        select collections).AsEnumerable().FirstOrDefault(); 

      if (dbCollection == null) 
      { 
       dbCollection = 
        await 
         _client.CreateDocumentCollectionAsync(database.SelfLink, 
          new DocumentCollection() {Id = dbCollectionBooks}); 
      } 

      Console.WriteLine("Connected to DocumentCollection" + dbCollection.Id); 
      //Document 
      string doucmentID = "BookDocument"; 
      Document document = (from documents in _client.CreateDocumentQuery(database.SelfLink) 
       where documents.Id == doucmentID 
       select documents).AsEnumerable().FirstOrDefault(); 
      if (document == null) 
      { 
       var _newBook = new Book(); 
       _newBook.Bookcase.Category = newBook.Bookcase.Category; 
       _newBook.ISBN = newBook.ISBN; 
       _newBook.Title = newBook.Title; 
       _newBook.Author = newBook.Author; 
       _newBook.RealeaseDate = newBook.RealeaseDate; 
       _newBook.Colour = newBook.Colour; 
       _newBook.Genre = newBook.Genre; 
       document = await _client.CreateDocumentAsync(dbCollection.SelfLink, _newBook); 
       BookContainer.Add(_newBook); 
      }    
     } 
    } 

回答

0

看起來像你正在尋找ReplaceDocumentAsync方法。

你的電話看起來像 await client.ReplaceDocumentAsync(document.SelfLink,_newBook);

請記住,如果您需要在更新之前檢查現有文檔的某些屬性,還可以使用特定類型(例如Book)創建文檔查詢。