c# - 如何从通用 DocumentDBRepository 中的 DocumentDB 文档模型读取类型名称?

标签 c# azure generics repository azure-cosmosdb

我有一个包含异构文档类型的 DocumentDB 集合。我的 DocumentDB 存储库基于 this GitHub project ,并且有GetItems方法如下:

    public IReadOnlyCollection<T> GetItems()
    {
        return Client.CreateDocumentQuery<T>(Collection.DocumentsLink).ToList();
    }

    public T GetItem(Expression<Func<T, bool>> predicate)
    {
        return Client.CreateDocumentQuery<T>(Collection.DocumentsLink)
            .Where(predicate)
            .AsEnumerable()
            .FirstOrDefault();
    }

存储库运行良好,但是当我实际上想按类型查询时,使用上述查询会返回我的所有文档。

多个来源(例如 this redditthis SO question )建议使用我的 DocumentModel 中内置的类型属性,因此我更新了我的 BaseDocument类(所有文档都继承自该类)以包含类型。 BaseDocument现在看起来像这样:

[Serializable]
public class BaseDocument
{
    [JsonProperty(PropertyName = "id")]
    public string Id { get; set; }

    [JsonProperty(PropertyName = "type")]
    public string Type { get; set; }

    public BaseDocument(string id, string type)
    {
        Id = id;
        Type = type;
    }
}

我尝试更改 GetItems 方法以包含类型字符串,如下所示:

public IReadOnlyCollection<T> GetItems(string type)
{    
    return Client.CreateDocumentQuery<T>(Collection.DocumentsLink,
        String.Format("SELECT * FROM collection c WHERE c.type = '{0}'", type)).ToList();
}

这可行,但每次我调用 GetItems() 时都必须通过魔术字符串似乎很笨拙。我想我可以在每个 FooDocument 中包含一个常量(每个扩展 BaseDocument )将指定类型名称,但我不知道如何在不传递它的情况下读取它。我怎样才能从我的 DocumentDbRepository<FooDocument> 中读取这个常量?类?

最佳答案

向返回类型的 BaseDocument 添加公共(public) get 属性 类似的东西(这里是伪代码,请耐心等待);

public string Type
    get {
        return this.GetType() // you can control if you want the FQN or just the name
    }

将以下内容添加到 GetItems 方法签名的末尾

where T : BaseDocument

现在您可以在您的存储库中执行类似的操作;

    return Client.CreateDocumentQuery<T>(Collection.DocumentsLink,
    String.Format("SELECT * FROM collection c WHERE c.type = '{0}'", T.Type)).ToList();

这消除了对常量的需要,并且您不必将类型作为参数传递给您的方法。

您甚至可以使用 LINQ 执行以下操作;

GetItems<T>(Predicate predicate) Where T : BaseDocument {
    return client.CreateDocumentQuery(collectionLink)
                .Where(predicate)
                .Where(d => d.Type == T.Type);
}

如果您希望我可以在某个地方分享/发布,我有一个工作存储库可以执行此操作。

关于c# - 如何从通用 DocumentDBRepository 中的 DocumentDB 文档模型读取类型名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32234088/

相关文章:

c# - 如何从 dataPackageView.GetDataAsync() 获取字符串

c# - 与 Windows 服务交谈

使用 Terraform 的 Azure 容器注册表权限

java - 如何创建比较器

java - 如何在 ResponseEntity<> 中传递未知类类型

java - 如何创建泛型?

C# 客户端应用程序与 Web 应用程序

c# - 需要 && 在一起不确定数量的 Func<TEntity, bool>

c# - 应如何将 IIS 托管的基于 ASP.Net 的系统部署到 Azure Service Fabric?

azure - 可以使用 Azure documentDb 支持 bi 在线工作