3

I have these 2 classes, Process and Task. Task is a related entity and is optional. I want to be able to map Task properties on select only if this is not null. How do i handle it?

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

on my razor page

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;}
}
Jackal
  • 3,359
  • 4
  • 33
  • 78

2 Answers2

3

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

Indunil Withana
  • 176
  • 1
  • 8
2
TaskDescription = p.Task?.Description

The code above will set TaskDescription to null if Task is null.

wserr
  • 436
  • 1
  • 3
  • 12
  • but won't this throw a null reference exception if Task is not initialized because doesn't exist and is trying to access null memory? – Jackal Nov 06 '19 at 09:29
  • 1
    https://stackoverflow.com/questions/28352072/what-does-question-mark-and-dot-operator-mean-in-c-sharp-6-0 this link provides a further detailed explanation on what the question mark operator does. Is this a solution for you? – wserr Nov 06 '19 at 09:31
  • I see i think i understand now. I know about terniary operator but i haven't used it like this before. Thanks for explaining – Jackal Nov 06 '19 at 09:32
  • Also just to add up that this does not work on the linq select. Have to do like @Indunil Withana said. It says cannot be used in an expression tree lambda – Jackal Nov 06 '19 at 09:36
  • 1
    There are indeed some expressions you can't use in a LINQ query against your context. I didn't consider that. You could also first retrieve your record from the database and then cast it to your PageViewModel. For further reference: https://stackoverflow.com/questions/44681362/an-expression-tree-lambda-may-not-contain-a-null-propagating-operator – wserr Nov 06 '19 at 09:47
  • 1
    That's not correct. It will return null, not an empty string – overcomer Nov 07 '19 at 09:15
  • Indeed. After testing it I see now that the question mark operator will return a null value instead of an empty string. I will edit my answer. Thank you for pointing it out @overcomer – wserr Nov 07 '19 at 09:36