1
votes

I have a document in RavenDB that contains a child collection. The child collection contains the following base type.

public class Section
{
    public string BackgroundColor { get; set; }
    public string Description { get; set; }
    public string DesktopBackgroundImageUrl { get; set; }
    public DateTime? EndDate { get; set; }
    public string MobileBackgroundImageUrl { get; set; }
    public int SortOrder { get; set; }
    public DateTime? StartDate { get; set; }
    public string TextColor { get; set; }
    public string Title { get; set; }
    public SectionType Type { get; set; }
}

There are a few derived classes from this type, one of which being this.

public class OfferSection : Section
{
    public IEnumerable<Merchant> Merchants { get; set; }
}

The problem I'm having is that I need to query this child collection and get the documents that contain the derived type and then query it's values.

This is where I've got to so far, however because it's using the base type, the Merchants property doesn't exist

public class Hubs_ByMerchantId : AbstractIndexCreationTask<Hub>
{
    public Hubs_ByMerchantId()
    {
        Map = hubs => from hub in hubs
            select new
            {
                Sections_Merchants_Id = hub.Sections.Where(x => x.Type == SectionType.Offer).SelectMany(x => x.Merchants.Select(y => y.Id))
            };
    }
}

Can anyone point me in the right direction?

Thanks

2

2 Answers

0
votes

You can use .OfType<Type> to get what ypou want:

hub.Sections.OfType<OfferSection>().SelectMany(x => x.Merchants.Select(y => y.Id));
0
votes

After a bit of messing about the way I got this to work was by casting it inside the select. This worked because we already have a type enum saved against the section so it's easy enough to do the cast.

public class Hubs_ByMerchantId : AbstractIndexCreationTask<Hub>
{
    public Hubs_ByMerchantId()
    {
        Map = hubs => hubs.SelectMany(x => (IEnumerable<OfferSection>)x.Sections).Where(x => x.Type == SectionType.Offer).Select(x => new
        {
            Sections_Merchants_Id = x.Merchants.Select(y => y.Id)
        });
    }
}

This probably isn't the best solution but it was the only thing that worked