【问题标题】:Convert returned document from DocumentDB to C# class with strict type checking通过严格的类型检查将返回的文档从 DocumentDB 转换为 C# 类
【发布时间】:2017-04-18 08:38:28
【问题描述】:

TEntity是Generic BaseClass,有两个类派生自BaseClassLocationEntityZoneEntity

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&lt;Document&gt;。我假设你的类继承自Document?如果是这样,为什么不对TEntity 使用通用约束?无论哪种方式,dynamic 演员表看起来都不合适。你不能改用is TEntityas TEntity 构造吗?另请注意,throw ex; 不会保留异常的堆栈跟踪 - throw; 会。
  • 我没有从 Document 继承.. 从来没有觉得需要。 readObj = response.Resource 因为 TEntity 给出了空值。感谢您提供有关前任的信息。
  • 那么ReadDocumentAsync返回的是什么类型的文档,你通常如何将其转换为LocationEntity?只是将演员表添加到 dynamic 然后再添加到您的目标类型不会神奇地起作用...
  • @PieterWitvoet 它正在发生。调用此类 (GetById) 的类正在传递 LocationEntity。
  • 我知道您将其称为GetById&lt;LocationEntity&gt;(...),但我要问的是:您通常如何(没有泛型)将Document 转换为LocationEntity?跨度>

标签: c# generics serialization azure-cosmosdb


【解决方案1】:

我最终用[JsonProperty(Required = Required.Always)]ZoneEntity 属性装饰了LocationEntity 的一些独特属性。
现在readObj = (TEntity) (dynamic) response.Resource; 会在属性不存在时抛出错误。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-24
    • 1970-01-01
    • 2021-06-16
    • 1970-01-01
    • 2013-01-09
    • 1970-01-01
    相关资源
    最近更新 更多