简体   繁体   中英

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'

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM