我想按tblInspection中的字段分组并在tblInspectionDate中选择最新的InspectionDate,但是我不知道如何引用Included表中的字段。
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类:
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类:
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; }
}
答案 0 :(得分:1)
您无需分组。我认为可以肯定地假设InspectionID
是Inspection
的主键,因此组始终包含一个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
。
旁注:从类和属性名称中删除这些令人讨厌的tbl
前缀,并使用复数名称作为集合。