c# - Entity Framework Core 映射相关实体,仅当它不为空时

标签 c# asp.net-core entity-framework-core razor-pages

我有这两个类,进程和任务。任务是一个相关的实体,是可选的。我希望仅当这不为 null 时才能够在 select 上映射 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;}
}

最佳答案

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

关于c# - Entity Framework Core 映射相关实体,仅当它不为空时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58726561/

相关文章:

c# - 如何使用其中一个变量对列表中的类进行排序

c# - 在 .NET Core 2.0 中合并 PDF 并将 PDF 转换为 PNG 图像

asp.net-core - 更改 ASP.Net Core 中 url 的 "/api"部分

c# - .net 核心注册通用接口(interface)并使用 getservice 检索它们

c# - 如何在 EF Core 中创建 DbContext 实例时传递 DbContextOptions 值

Linq where 条件 on datetime.ToString()

c# - XML声音的字节格式

c# - "There was an error sending this message to your bot: HTTP status code NotFound"

c# - 如何使 List<List<int>> *.cshtml/razor - 兼容?

c# - 处理 Entity Framework 核心中的并发条件以防止竞争条件