【发布时间】:2015-08-27 03:23:10
【问题描述】:
我有一个包含异构文档类型的 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 reddit 和this SO question)建议使用内置在我的DocumentModels 中的类型属性,因此我更新了我的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> 类中读取此常量?
【问题讨论】:
标签: c# azure generics repository azure-cosmosdb