C# 使用Azure DocumentDB并将对象添加到文档

C# 使用Azure DocumentDB并将对象添加到文档,c#,azure-cosmosdb,C#,Azure Cosmosdb,我正在开发一个库应用程序,也就是说,它必须连接到Azure DocumentDB。在我的DocumentDB中,我有一个DocumentCollection,即BookCollection和一个Document-BookDocument。每次向系统中添加新书时,都必须使用新书对象更新此文档,我的问题是:我如何做到这一点?到目前为止,我有: public static async Task AddBook(Book newBook) { using (_client = new DocumentC

我正在开发一个库应用程序,也就是说,它必须连接到Azure DocumentDB。在我的DocumentDB中,我有一个DocumentCollection,即BookCollection和一个Document-BookDocument。每次向系统中添加新书时,都必须使用新书对象更新此文档,我的问题是:我如何做到这一点?到目前为止,我有:

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);
            }               
        }
    }

看起来您正在寻找replaceDocumentSync方法

你的电话看起来像 等待client.ReplaceDocumentAsync(document.SelfLink,_newBook)

请记住,如果需要在更新现有文档之前检查其某些属性,您还可以创建具有特定类型(例如Book)的文档查询