我在 RavenDB 的单个文档中保存了一个类别层次结构。
"CategoryList": [
{
"$id": "1",
"Id": "Admin",
"Name": "Administration",
"ParentCategory": null,
"Subcategories": [
{
"$id": "2",
"Id": "Admin1",
"Name": "Administration 1",
"ParentCategory": {
"$ref": "1"
},
"Subcategories": []
},...
我可以使用这两个类在 C# 中成功加载它
public class Categories
{
public string Id { get; set; }
public IEnumerable<Category> CategoryList{ get; set; }
}
[JsonObject(IsReference = true)]
public class Category
{
private readonly IList<Category> _subcategories;
public string Id { get; set; }
public string Name { get; set; }
public Category ParentCategory { get; set; }
public IEnumerable<Category> Subcategories
{
get { return _subcategories; }
}
public Category()
{
_subcategories = new List<Category>();
}
public void AddSubcategory(Category subcategory)
{
subcategory.ParentCategory = this;
_subcategories.Add(subcategory);
}
}
但现在我想查询我的类别层次结构以通过其 Id 检索单个类别。我怎么能那样做?每个类别创建一个文档会更好吗?
谢谢
更新:
嗨,艾扬德,
谢谢回复。我相信Hierarchy
您文章中使用的方法已经过时,但我能够找到新版本......
阅读本文后,我创建了一个返回所有类别的索引:
public class CategoriesByIdIndex : AbstractIndexCreationTask<Categories, CategoriesByIdIndex.ReduceResult>
{
public class ReduceResult
{
public string Id { get; set; }
public Category Category { get; set; }
}
public CategoriesByIdIndex()
{
Map = categoriesCollection => from categories in categoriesCollection
from category in categories.CategoryList
from subcategory in category.Hierarchy(x => x.Subcategories)
select new
{
subcategory.Id,
Category = subcategory
};
Store(x => x.Id, FieldStorage.Yes);
Store(x => x.Category, FieldStorage.Yes);
}
}
当我执行此查询时,将返回所有类别:
var allCategories = session.Query<Categories, CategoriesByIdIndex>()
.AsProjection<CategoriesByIdIndex.ReduceResult>()
.ToList();
但是当我尝试按类别 ID 过滤它时,我收到一个空列表:
var singleCategory = session.Query<Categories, CategoriesByIdIndex>()
.AsProjection<CategoriesByIdIndex.ReduceResult>()
.Where(x => x.Id == "Admin1")
.ToList();
我究竟做错了什么?
谢谢