Chaddeus
Chaddeus

Reputation: 13356

In RavenDB, how to query for nested "objects" in the document?

If I have stored documents which look like this:

Category {
    public string Id {get;set;}
    public List<Category> Categories {get;set;}
    ...
}

Essentially a category, with sub-categories. In my case, only ever 2 levels deep (1 parent, n sub-categories).

Querying for all categories works great, showing a nice list (with nested sub-category lists too). My users can only click a sub-category, to view things within selected category. I want to pull 1 of the sub-categories out, as a Category.

Given a sub-category Id, how would I pull one of the sub-categories out as it's own stand-alone Category?

Update

I'd like to add, I am getting around this by doing this:

        Category pCat = RavenSession.Query<Category>().Where(x => x.Categories.Any(c => c.Id == id)).FirstOrDefault();
        Category cat = pCat.Categories.Where(x => x.Id == id).FirstOrDefault();

Which first gets the category which contains the sub-category, then queries the sub-categories on that category to pull the specific sub-category.

Perhaps this is better, I don't know... but seems like it's doing 2 steps when 1 could suffice.

Update 2

All id's in these categories are manually added, no RavenDB auto id's (even the sub-categories have an Id).

Upvotes: 1

Views: 2601

Answers (1)

Thinking Sites
Thinking Sites

Reputation: 3542

Your Categories property holds a list of object, where instead you can have the ids of the nested categories. The child categories, the way you have it built, will not have ids, only data.

Category {
    public string Id {get;set;}
    public List<Category> Categories {get;set;}
    ...
}

Instead try this model and this query:

Category {
    public string Id {get;set;}
    public List<string> CategoryIDs {get;set;}
    ...
}

var parent = session
    .Include(i => i.CategoryIDs)
    .Load<Category>("category/1");

var children= session.Load<Category>(parent.CategoryIDs);

A caveat: I haven't tested this code since I don't have a project to test it in right now, but here are my sources:

  1. http://ayende.com/blog/4584/ravendb-includes
  2. RavenDB Include - Session.Load<T>(string[] ids)
  3. http://richarddingwall.name/2012/03/08/ravendb-includes-much-simpler-than-you-think/

Upvotes: 2

Related Questions