如何编写索引以在RavenDB中跨文档获取集合中的对象总数?

时间:2014-01-16 22:12:23

标签: c# ravendb

我有以下对象,我将其作为文档保存在我的数据库中:

public class ClientContactsModel
{
    public ClientContactsModel()
    {
        Contacts = new List<ContactItem>();
    }

    public Guid Id { get; set; }
    public Guid ClientId { get; set; }
    public List<ContactItem> Contacts { get; set; }
}

如何编写索引来计算每个ClientContactsModel对象中的联系人数量,以获得联系人总数?

1 个答案:

答案 0 :(得分:2)

我能够解决这个问题:

public class Contacts_GetCount: AbstractIndexCreationTask<ClientContactsModel, Contacts_GetCount.ContactResult>
{
    public class ContactResult
    {
        public Guid ClientId { get; set; }
        public int Total { get; set; }
    }

    public Contacts_GetCount()
    {
        Map = contacts => from contact in contacts
            select new {
                ClientId = contact.ClientId,
                Total = contact.Contacts.Count
            };

        Reduce = results => from result in results
            group result by result.ClientId
            into g
            select new {
                ClientId = g.Key,
                Total = g.Sum(x=>x.Total)
            };
    }
}

我遗失的那篇文章是在文档的映射中将创建的匿名类型的集合计数。