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

通过严格的类型检查将返回的文档从DocumentDB转换为C#类,c#,generics,serialization,azure-cosmosdb,C#,Generics,Serialization,Azure Cosmosdb,tenty是泛型基类,有两个类派生自基类LocationEntity和ZoneEntity public async Task<TEntity> GetById(string id) { TEntity readObj = null; try { var response = await client.ReadDocumentAsync(UriFactory.CreateDocumentUri

tenty
是泛型基类,有两个类派生自基类
LocationEntity
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;
    }
下面的
GetById()
具有
LocationEntity
的上下文,但是
响应。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;
    }
公共异步任务GetById(字符串id)
{
tenty readObj=null;
尝试
{
var response=await client.readdocumentsync(UriFactory.CreateDocumentUri(dbName,collectionName,id),
请求选项);
readObj=(tenty)(dynamic)response.Resource;//它忽略了与tenty(LocationEntity)不匹配的属性
}
捕获(例外情况除外)
{
掷骰子;
}
返回readObj;
}
如何在将DocuementDB
文档
转换为
tenty
时执行严格的类型检查


响应时,我想抛出异常或其他东西。Resource
不是
LocationEntity

类型,我最后用
[JsonProperty(Required=Required.Always)]
装饰了
LocationEntity
的一些独特属性,而
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;
    }
现在
readObj=(tenty)(dynamic)response.Resource引发错误


这是我找到的一种方法,但仍希望找到更好的方法。

readdocumentsync
返回
resourcesponse
。我假设您的类继承自
文档
?如果是这样,为什么不在
tenty
上使用通用约束?无论哪种方式,动态的演员阵容看起来都不合适。你不能用
是tenty
作为tenty
结构吗?还要注意,
抛出ex不保留异常的堆栈跟踪-
抛出是。我不是从文档继承的。。从来没有感觉到需要。readObj=response.Resource as tenty为null。感谢您提供有关ex的信息。那么,
ReadDocumentSync
返回的是哪种文档,您通常如何将其转换为
LocationEntity
?仅仅在
dynamic
中添加一个cast,然后在目标类型中添加一个cast,并不能神奇地起作用…@PieterWitvoet,事情正在发生。调用此类(GetById)的类正在传递LocationEntity。我知道您将其称为
GetById(…)
,但我要问的是:您通常如何(没有泛型)将
文档
转换为
LocationEntity