Search code examples
azure-cosmosdbasp.net-core-2.0document-database

convert object to DocumentDb Document in .Net Core


I have the following code which takes in a object of type employee based on it's model, I want to convert this to a DocumentDB Document then post to the database. How would I do the conversion?

[HttpPost]
        public async Task Post([FromBody]Employee employee)
        {
            using (_logger.BeginScope("Post employee"))
            {
                try
                {
                    // convert employee to Document??
                    await _documentDbRepository.CreateItemsAsync(document);
                }
                catch (Exception e)
                {
                    _logger.LogError(e.Message);
                    throw;
                }

            }
        }

Solution

  • It seems that you're using a custom layer over top of the regular Cosmos libraries which is hard coded to only accept a Document. The libraries supplied by Microsoft are capable of inserting any generic object and will use default JSON serialization to turn it into a Document for you at insert time. Changing the signature on your custom repository to accept Object instead of Document should get you unblocked.