[英]Entity Framework Core map related entity only if it's not null
我有這兩個類,進程和任務。 任務是一個相關實體,是可選的。 我希望能夠在 select 上的 map 任務屬性,前提是這不是 null。 我該如何處理?
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
TaskDescription = p.Task?.Description
如果 Task 是 null,上面的代碼會將 TaskDescription 設置為 null。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.