如果我想基于CosmoDb中的接口返回对象,该怎么办? 我的界面:
namespace Test
{
public interface IPerson
{
int Age { get; set; }
}
public class Person : IPerson
{
public int Age { get; set; }
}
}
我的CosmosDb方法:
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;
}
我遇到错误:
Unable to cast object of type 'Microsoft.Azure.Documents.Document' to type 'CabbyTech.FleetOps.Classes.IFleet'.
我应该如何将回复传递给个人或IPerson?
答案 0 :(得分: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;
}
}
只需更改它以适合您的代码,在这里我使用JsonConvert来获取类型