1

我需要根据相关实体中某个字段的最大值查询相关实体,然后显示该项目的结果。

例如,模型定义为:

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:可空对象必须有一个值。

4

1 回答 1

0

在 Max 语句之后,我无法查询其他字段。我尝试了一些方法来实现过滤相关数据的结果。

是的!你不能!因为Max语句仅选择您在Max.

当学生没有 ReportCard 时,它也不处理这种情况。InvalidOperationException:可空对象必须有一个值。

执行以下操作以克服这两个问题:

@foreach (Student student in Model.Students)
{
    <p>@student.Name</p>

    if(student.ReportCards.Count > 0)
    {
      <p>@student.ReportCards.OrderByDescending(rc => rc.PublishDate).FirstOrDefault().Result.ToString()</p>

      <p>@student.ReportCards.OrderByDescending(rc => rc.PublishDate).FirstOrDefault().PublishDate.ToString()</p>
    }
    else
    {
      <p>Student has no report card!</p>
    }

}
于 2018-12-12T04:04:54.410 回答