Entity Framework Core 仅在相关实体不为 null 时进行映射

3

我有这两个类,Process和Task。Task是相关实体,是可选的。如果Task不为空,我希望能够映射Task属性只选择它。我该如何处理?

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;}
}

在我的 Razor 页面上
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;}
}
2个回答

3

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


2
TaskDescription = p.Task?.Description

如果任务为空,上述代码将把TaskDescription设置为null。

1
这个链接提供了更详细的解释,关于问号运算符在C# 6.0中的作用。这对你来说是一个解决方案吗? - wserr
我看到了,我想我现在明白了。我知道三元运算符,但以前没有像这样使用过。谢谢你的解释。 - Jackal
1
确实有一些表达式不能在对上下文的LINQ查询中使用。我没有考虑到这一点。您也可以先从数据库检索记录,然后将其转换为PageViewModel。更多参考信息:https://dev59.com/ElcP5IYBdhLWcg3wP32t - wserr
1
那不正确。它将返回 null,而不是空字符串。 - overcomer
确实。在测试后,我现在看到问号运算符将返回一个null值而不是空字符串。我会编辑我的答案。感谢您指出这一点@overcomer。 - wserr
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接