如何从通用DocumentDBRepository中的DocumentDB文档模型中读取类型名称
本文关键字:模型 读取 取类型 文档 DocumentDB 中的 DocumentDBRepository | 更新日期: 2023-09-27 18:10:08
我有一个具有异构文档类型的DocumentDB集合。我的DocumentDB存储库基于这个GitHub项目,并具有如下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();
}
存储库运行良好,但使用上面的查询,当我真正想按类型查询时,我的所有文档都会返回。
有几个来源(比如这个reddit和这个SO问题(建议使用我的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>
类中读取这个常量?
将公共get属性添加到返回类型的BaseDocument类似于(这里的伪代码,请耐心等待(;
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);
}
我有一个工作回购,如果你愿意,我可以在某个地方分享/发布。