c# - RavenDB - 如何查询对象的属性及其子对象

标签 c# .net nosql ravendb

我的问题是根据每个文档的属性及其子文档的属性从 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 ==“There”的子对象?查询应解析为 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>()

关于c# - RavenDB - 如何查询对象的属性及其子对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17766808/

相关文章:

couchdb - 是否有任何文档数据库的设计指南?

c# - 使用 QBFC 时的 HRESULT 80040154

c# - 在运行时加载依赖程序集时是否可以运行单元测试?

c# - 从 .net core 2.0 中动态加载的程序集调试代码

java - .NET 应用程序的部署与 Java Web 应用程序的部署相比如何?

python - ArangoDB:尝试使用 gharial 接口(interface)创建顶点时出现服务器错误

database - 用于文件系统存储组织和复制的 NoSQL?

c# - 根据 bool 值更改椭圆的颜色

c# - 如何使用相同的通用方法来验证不同类型

c# - 需要使用数据库表架构在 .net 中获取空数据表