Reputation: 901
I want to create a basic nested index that contains just the id of the containing document and the nested data. Following the ravenDb documentation I did it as follows:
public class LeaguesIndex : AbstractIndexCreationTask<CommunityDocument>
{
public class Result
{
public string CommunityId { get; set; }
public Domain.TeamLeague League { get; set; }
}
public LeaguesIndex()
{
Map = communities => from community in communities
from league in community.TeamLeagues
select new
{
CommunityId = community.Id.Replace("CommunityDocuments/", string.Empty),
League = league
};
}
}
And query it:
var leagues = session
.Query<LeaguesIndex.Result, LeaguesIndex>()
.Where(x => x.CommunityId == input.Id)
.OfType<CommunityDocument>()
.ToList();
This did yield a result, except the result contained the entire CommunityDocument. How can I do it so that I just get the LeaguesIndex.Result class? (I tried removing 'OfType' line, but it didn't like it.)
edit - This is working:
public class LeaguesIndex : AbstractIndexCreationTask<CommunityDocument, LeaguesIndex.Result>
{
public class Result
{
public string CommunityId { get; set; }
public Domain.League League { get; set; }
}
public LeaguesIndex()
{
Map = communities => from community in communities
from league in community.TeamLeagues
select new
{
CommunityId = community.Id.Replace("CommunityDocuments/", string.Empty),
League = league
};
StoreAllFields(FieldStorage.Yes);
}
}
query:
var lastLeague = session
.Query<LeaguesIndex.Result, LeaguesIndex>()
.Where(x => x.CommunityId == input.Id)
.AsProjection<LeaguesIndex.Result>()
.LastOrDefault();
Upvotes: 0
Views: 76
Reputation: 387
For RavenDB 3.5, you should use ProjectFromIndexFieldsInto
:
var lastLeague = session
.Query<LeaguesIndex.Result, LeaguesIndex>()
.Where(x => x.CommunityId == id)
.ProjectFromIndexFieldsInto<LeaguesIndex.Result>()
.LastOrDefault();
See https://ravendb.net/docs/article-page/3.5/Csharp/client-api/session/querying/how-to-perform-projection for details.
Note from the linked documentation:
Projections request from server an array of fields to download, if index contains those fields (stores them) they will come directly from index, if not values from document will be used.
This means that unless you store the data in the index, the data will be loaded from documents, slowing down the performance.
Old answer assuming RavenDB 4.0:
Use ProjectInto<T>
:
var leagues = session
.Query<LeaguesIndex.Result, LeaguesIndex>()
.Where(x => x.CommunityId == input.Id)
.ProjectInto<LeaguesIndex.Result>()
.ToList();
See https://ravendb.net/docs/article-page/4.0/csharp/indexes/querying/projections#projectinto for more detail.
Upvotes: 2