使用严格的类型检查将返回的文档从DocumentDB转换为C#类

时间:2017-04-18 08:38:29

标签: c# generics serialization azure-cosmosdb

NSKeyedArchiver是Generic BaseClass,有两个派生自BaseClass TEntityLocationEntity的类。

ZoneEntity下方的上下文为GetById(),但LocationEntity返回response.Resource的对象。

ZoneEntity

如何在将DocuementDB public async Task<TEntity> GetById(string id) { TEntity readObj = null; try { var response = await client.ReadDocumentAsync(UriFactory.CreateDocumentUri(dbName, collectionName, id), requestOptions); readObj = (TEntity) (dynamic) response.Resource; // it's ignoring the properties which does not match with TEntity (LocationEntity) } catch (Exception ex) { throw ex; } return readObj; } 转换为Document时执行严格类型检查?

我想在TEntity不属于response.Resource类型时抛出异常或其他内容。

1 个答案:

答案 0 :(得分:1)

我最终使用LocationEntity装饰了[JsonProperty(Required = Required.Always)]的一些独特属性,并为ZoneEntity属性添加了相同属性。
如果属性不在那里,readObj = (TEntity) (dynamic) response.Resource;会抛出错误。

这是我想出来的一种方式,但仍希望有更好的方法。