LINQ 分组依据包含 table

LINQ group by with included table

我想按 tblInspection 中的字段和 select tblInspectionDate 中最近的 InspectionDate 进行分组,但我不知道如何引用 Included table 中的字段。

public IEnumerable<InspectionEvent> GetInspectionEvents() //string facilityID)
    {
        using (var context = new FacilityEntities())
        {
            var inspections = context.tblInspection.AsNoTracking().Include("tblInspectionDate");
            List<InspectionEvent> inspectionList =
                (from insp in inspections
                     group insp by new { insp.InspectionID, insp.Inspection, insp.Inspector, insp.FacilityID, insp.InventoryID, insp.Period }  
                     into g
                         select new InspectionEvent
                         {
                             InspectionID = g.Key.InspectionID,
                             InspectionName = g.Key.Inspection,
                             Inspector = g.Key.Inspector,
                             FacilityID = g.Key.FacilityID,
                             InventoryID = g.Key.InventoryID,
                             Period = g.Key.Period,
                             InspectionDate = g.Max(x => x.tblInspectionDate.InspectionDate? something like this?)
                         }).ToList();
            return inspectionList;
        }
    }

这是 tblInspection class:

public partial class tblInspection
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public tblInspection()
    {
        this.tblInspectionDate = new HashSet<tblInspectionDate>();
    }

    public int InspectionID { get; set; }
    public string Inspection { get; set; }
    public string Inspector { get; set; }
    public Nullable<int> FacilityID { get; set; }
    public Nullable<int> InventoryID { get; set; }
    public string Period { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<tblInspectionDate> tblInspectionDate { get; set; }
}

和 tblInspectionDate class:

public partial class tblInspectionDate
{
    public int InspectionID { get; set; }
    public System.DateTime InspectionDate { get; set; }
    public int UserID { get; set; }

    public virtual tblInspection tblInspection { get; set; }
    public virtual tblUser tblUser { get; set; }
}

不需要分组。我认为假设 InspectionIDInspection 的主键是安全的,因此一个组总是包含一个 Inspection,这使得分组毫无意义。你想要的可以相对简单地通过以下方式查询:

from insp in inspections
select new InspectionEvent
{
    InspectionID = insp.InspectionID,
    InspectionName = insp.Inspection,
    Inspector = insp.Inspector,
    FacilityID = insp.FacilityID,
    InventoryID = insp.InventoryID,
    Period = insp.Period,
    InspectionDate = (DateTime?)insp.tblInspectionDate.Max(d => d.InspectionDate)
}

转换为 DateTime? 是为了考虑没有任何 tblInspectionDate 的检查。

旁注:从 class 和 属性 名称中删除这些繁琐的 tbl 前缀,并为集合使用复数名称。