【发布时间】:2017-04-18 08:38:28
【问题描述】:
TEntity是Generic BaseClass,有两个类派生自BaseClassLocationEntity和ZoneEntity。
GetById() 下方有LocationEntity 的上下文,但response.Resource 正在返回ZoneEntity 的对象。
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;
}
如何在将DocuementDB Document 转换为TEntity 时执行严格的类型检查?
当response.Resource 不是LocationEntity 类型时,我想抛出异常或其他东西。
【问题讨论】:
-
ReadDocumentAsync返回一个ResourceResponse<Document>。我假设你的类继承自Document?如果是这样,为什么不对TEntity使用通用约束?无论哪种方式,dynamic演员表看起来都不合适。你不能改用is TEntity或as TEntity构造吗?另请注意,throw ex;不会保留异常的堆栈跟踪 -throw;会。 -
我没有从 Document 继承.. 从来没有觉得需要。 readObj = response.Resource 因为 TEntity 给出了空值。感谢您提供有关前任的信息。
-
那么
ReadDocumentAsync返回的是什么类型的文档,你通常如何将其转换为LocationEntity?只是将演员表添加到dynamic然后再添加到您的目标类型不会神奇地起作用... -
@PieterWitvoet 它正在发生。调用此类 (GetById) 的类正在传递 LocationEntity。
-
我知道您将其称为
GetById<LocationEntity>(...),但我要问的是:您通常如何(没有泛型)将Document转换为LocationEntity?跨度>
标签: c# generics serialization azure-cosmosdb