【问题标题】:RavenDB query child collection polymorphismRavenDB 查询子集合多态性
【发布时间】:2017-09-20 18:05:00
【问题描述】:

我在 RavenDB 中有一个包含子集合的文档。子集合包含以下基本类型。

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

这个类型有几个派生类,其中之一就是this。

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

谁能指出我正确的方向?

谢谢

【问题讨论】:

    标签: c# ravendb nosql


    【解决方案1】:

    您可以使用.OfType&lt;Type&gt; 来获得您想要的:

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

    【讨论】:

    • 这不起作用。 Raven 返回一个错误,说它无法理解 OfType()
    • 它适用于我,如果我有 Hub 类,其中包含属性 public IEnumerable&lt;Section&gt; Sections { get; set; } 请在代码中添加关于什么是中心的信息。
    • 上面的代码是我的。 OfType() 适用于普通对象,但是我不能在 Raven 索引中使用它,因为 Raven 抛出一个错误,说它不明白如何处理 OfType()
    【解决方案2】:

    在搞砸了我让它工作的方式之后,我将它投射到了选择中。这很有效,因为我们已经针对该部分保存了一个类型枚举,因此很容易进行强制转换。

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

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

    【讨论】:

      猜你喜欢
      • 2016-05-21
      • 1970-01-01
      • 2013-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多