我需要根据相关实体中某个字段的最大值查询相关实体,然后显示该项目的结果。
例如,模型定义为:
public class Student
{
public int StudentID {get; set;}
public string Name {get; set;}
public ICollection<ReportCard> ReportCards {get; set;}
}
public class ReportCard
{
public int ReportCardID {get; set;}
public int ProjectID { get; set; }
public Project Project { get; set; }
public int Result {get; set;}
public int Comment {get; set;}
public DateTime PublishDate {get; set;}
}
在剃须刀控制器中:
public class LatestResultsModel : PageModel
{
...
public IList<Student> Students {get; set;}
public async Task<IActionResult> OnGetAsync()
{
Students = await _context.Student
.Include(student => student.ReportCard)
.ToListAsync();
}
}
在剃刀视图中:
@foreach (Student student in Model.Students)
{
<p>@student.Name</p>
<p>@student.ReportCard.Max(i => i.PublishDate).Result.ToString()</p>
}
在 Max 语句之后,我无法查询其他字段。我尝试了一些方法来实现过滤相关数据的结果。
是否有某种类型的连接可以实现此结果?
当学生没有 ReportCard 时,它也不处理这种情况。InvalidOperationException:可空对象必须有一个值。