我想创建一个基本的嵌套索引,它只包含包含文档的id和嵌套数据。在ravenDb文档之后,我做了如下:
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
};
}
}
查询它:
var leagues = session
.Query<LeaguesIndex.Result, LeaguesIndex>()
.Where(x => x.CommunityId == input.Id)
.OfType<CommunityDocument>()
.ToList();
这确实产生了结果,但结果包含整个CommunityDocument。我该怎么做才能获得LeaguesIndex.Result类? (我尝试删除'OfType'行,但它不喜欢它。)
编辑 - 这是有效的:
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);
}
}
查询:
var lastLeague = session
.Query<LeaguesIndex.Result, LeaguesIndex>()
.Where(x => x.CommunityId == input.Id)
.AsProjection<LeaguesIndex.Result>()
.LastOrDefault();
答案 0 :(得分:2)
对于RavenDB 3.5,您应该使用ProjectFromIndexFieldsInto
:
var lastLeague = session
.Query<LeaguesIndex.Result, LeaguesIndex>()
.Where(x => x.CommunityId == id)
.ProjectFromIndexFieldsInto<LeaguesIndex.Result>()
.LastOrDefault();
请注意链接文档:
投影从服务器请求要下载的字段数组,如果索引包含那些字段(存储它们),它们将直接来自索引,否则将使用来自文档的值。
这意味着除非您将数据存储在索引中,否则数据将从文档中加载,从而降低性能。
假设RavenDB 4.0的旧答案:
使用ProjectInto<T>
:
var leagues = session
.Query<LeaguesIndex.Result, LeaguesIndex>()
.Where(x => x.CommunityId == input.Id)
.ProjectInto<LeaguesIndex.Result>()
.ToList();
有关详细信息,请参阅https://ravendb.net/docs/article-page/4.0/csharp/indexes/querying/projections#projectinto。