代码之家  ›  专栏  ›  技术社区  ›  Scott Bamforth

RavenDB查询子集合多态性

  •  1
  • Scott Bamforth  · 技术社区  · 7 年前

    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; }
    }
    

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

    我遇到的问题是,我需要查询这个子集合,获取包含派生类型的文档,然后查询其值。

    Merchants 属性不存在

    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))
                };
        }
    }
    

    有人能给我指出正确的方向吗?

    谢谢

    2 回复  |  直到 7 年前
        1
  •  0
  •   Damian Miłosz    7 年前

    您可以使用 .OfType<Type> 要得到你想要的:

    hub.Sections.OfType<OfferSection>().SelectMany(x => x.Merchants.Select(y => y.Id));
    
        2
  •  0
  •   Scott Bamforth    7 年前

    经过一点混乱后,我得到了这个工作的方式是通过铸造内选择它。这是有效的,因为我们已经针对该节保存了一个类型枚举,因此可以很容易地进行转换。

    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)
            });
        }
    }
    

    这可能不是最好的解决方案,但它是唯一有效的方法