Search code examples
c#linqicollection

How to group by a nested property of ICollection in LINQ?


I need some help... I have an Entity with an ICollection nested, when I need to make a group by of Work (AdjudicationHead) and AdjYearFFI I cannot set AdjYearFFI as property to group.

Entities:

 public class AdjudicationHead : BaseEntity
 {
     public virtual int Work { get; set; }
     public virtual int AdjYear { get; set; }
     public virtual string AdjType { get; set; }
     public virtual long AdjNumber { get; set; }
     //Navigation
     public virtual ICollection<AdjudicationDetail> AdjudicationDetails { get; set; }
 }

public class AdjudicationDetail : BaseEntity
{
    public virtual int AdjYearFFI { get; set; }

    //FK
     public virtual int AdjYear { get; set; }
     public virtual string AdjType { get; set; }
     public virtual long AdjNumber { get; set; }
    //Navigation
    public virtual AdjudicationHead AdjudicationHead { get; set; }
}

This is what i tried:

public object GetDataCurvaInversionActual()
{
    var query = UoW.GetRepository<AdjudicationHead>()
    .GroupBy(q => new { q.Work, q.AdjudicationDetails.AdjYearFFI });
    var entities = query.ToList();
    var result = Mapper.Map<IList<AdjudicationHead>, IList<Dtos.AdjudicationHead>>(entities);
    return result;
}

Error:

'System.Collections.Generic.ICollection does not contain a definition for AdjYearFFI'


Solution

  • The problem here is that an ICollection<AdjudicationDetail> is a collection of AdjudicationDetail, not a AdjudicationDetail (as commented), and so it doesn't have a AdjYearFFI property. It would have only the properties of an ICollection type.

    If you want to group AdjudicationDetail's, you can use this query:

    var query = UoW.GetRepository<AdjudicationDetail>()
    .GroupBy(d => new { d.AdjudicationHead.Work, d.AdjYearFFI });
    

    Now, in your query you have a keyed collection, where your key have an anonymous type with a Work and a AdjYearFFI fields, and the element have a AdjudicationDetail object.