通过严格的类型检查将返回的文档从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
?