0

If I want to return an object based on a Interface in CosmoDb how would I do it? My Interface:

namespace Test
{
   public interface IPerson
   {
        int Age { get; set; }
   }

   public class Person : IPerson
   {
      public int Age { get; set; }

   }
}

My CosmosDb method:

    public async Task<IPerson> FleetUpdate(IPerson person)
     try
        {
            var res = await docClient.UpsertDocumentAsync(UriFactory.CreateDocumentCollectionUri(dbname, colName), person);

            IPerson person = (dynamic)res.Resource;
            return person;
        }
        catch (Exception ex)
        {

            throw ex;
        }

I am getting an error:

 Unable to cast object of type 'Microsoft.Azure.Documents.Document' to type 'CabbyTech.FleetOps.Classes.IFleet'.

How should I cast the response to a Person or IPerson?

Paul Stanley
  • 1,999
  • 1
  • 22
  • 60

1 Answers1

1
    public async Task<T> GetByIdAsync(Guid id)
    {
        try
        {
            var cosmosDbClient = CosmosDbClient();
            var document = await cosmosDbClient.ReadDocumentAsync(id, new RequestOptions
            {
                PartitionKey = ResolvePartitionKey(id)
            });

            return JsonConvert.DeserializeObject<T>(document.ToString());
        }
        catch (DocumentClientException e)
        {
            if (e.StatusCode == HttpStatusCode.NotFound)
            {
                throw new EntityNotFoundException();
            }

            throw;
        }
    }

just change it to fit your code, here i use JsonConvert to get the type back

JohnnBlade
  • 4,261
  • 1
  • 21
  • 22