RavenDB-如何查询两个对象';的属性及其子项
本文关键字:属性 两个 何查询 查询 RavenDB- 对象 | 更新日期: 2023-09-27 18:24:00
我的问题是根据每个文档的属性及其子文档的属性从C#中选择RavenDB文档。假设我们有以下文件:
objekts/1:
{
"Code": "1",
"Children": [
{
"Role": "A",
"Place": "Here"
},
{
"Role": "B",
"Place": "There"
}
]
}
objekts/2:
{
"Code": "1",
"Children": [
{
"Role": "A",
"Place": "There"
},
{
"Role": "B",
"Place": "Here"
}
]
}
我如何在C#中形成查询以选择具有Code=="的对象;1〃;以及至少一个具有Role="的孩子;A";并且Place=";那里"?查询应解析为objekts/2
。
此外,我如何制定一个可以查询的相应Raven索引?
数据类
public class Child
{
public string Role { get; set; }
public string Place { get; set; }
}
public class Objekt
{
public string Code { get; set; }
public List<Child> Children { get; set; }
}
首先,我们将处理索引,注意子键的前缀是Children_
(Raven需要):
public class Objekt_ByCodeAndChildren : AbstractIndexCreationTask<Objekt>
{
public Objekt_ByCodeAndChildren()
{
Map = objekts => from objekt in objekts
from child in objekt.Children
select new
{
objekt.Code,
Children_Role = child.Role,
Children_Place = child.Place
};
}
}
查询本身:
session.Query<Objekt, Objekt_ByCodeAndChildren>()
.Where(o => o.Code == "1" &&
o.Children.Any(c => c.Role == "A" && c.Place == "There"));
此查询成功地找到了ID为objekts/2
的文档,因为子关键字与o.Children.Any(c => c.Role == "A" && c.Place == "There")
匹配,所以需要在索引子关键字前面加上Children_
(例如Children_Role
)。
另一种技术是查询索引键类型,并将结果转换为原始类型(例如Objekt
):
// Index key representation of an Objekt
public class ObjektKey
{
public string Code { get; set; }
public string Role { get; set; }
public string Place { get; set; }
}
// Query for ObjektKey instances, before finally transforming them to Objekt
session.Query<ObjektKey, Objekt_ByCodeAndChildren>()
.Where(o => o.Code == "1" && o.Role == "A" && o.Place == "Here")
.OfType<Objekt>()