2016-03-09 112 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)创建文档查询。