Entity Framework 核心地图相关实体仅当它不为空时

Entity Framework Core map related entity only if it's not null

我有这 2 个 类,进程和任务。任务是一个相关的实体,是可选的。仅当这不为空时​​,我才希望能够在 select 上映射任务属性。我该如何处理?

public class Process
{
    public int Id {get;set;}
    public string Description {get;set;}
    public int? TaskId {get;set;}
    public Task Task {get;set;}
}

public class Task
{
    public int Id {get;set;}
    public string Description {get;set;}
}

在我的剃须刀页面上

public PageViewModel Process {get;set;}
[BindProperty(SupportsGet = true)]
public int Id { get; set;}
public void OnGet()
{
    Process = _context.Processes
                  .Select(p => new PageViewModel
                  {
                      Id = p.Id,
                      Description = p.Description,
                      HasTask = p.TaskId.HasValue,
                      TaskDescription = p.Task.Description // How to handle if task is null here?
                  })
                  .FirstOrDefault(p => p.Id == Id)

}

public class PageViewModel
{
    public int Id{get;set;}
    public string Description {get;set;}
    public bool HasTask {get;set;}
    public string TaskDescription {get;set;}
}

p.Task == null ? "" : p.Task.Description

TaskDescription = p.Task?.Description

如果 Task 为 null,上面的代码会将 TaskDescription 设置为 null。