Entity Framework Core: How to include a null related Entity with its null column properties?

Viewed 1199

I'm working on a project which uses EF Core and .Net Core.

I have 2 Entity classes. They are one-to-many relationships. Let say 'Student' N <-----> 1 'Grade'.

public class Student{
  public string Id {get;set;}
  public string Name {get;set;}
  public string GradeId {get;set;}
  public Grade grade {get;set;}
}

public class Grade{
  public string Id {get;set;}
  public string StudentGrade {get;set;}
}

My LINQ to eager load student like this

_dbcontext.Student.Include(s => s.Grade).ToList();

Sometimes, I create a "Student" record but I don't set "Grade" for it. As the result, the Grade will be null. Since I use WebAPI for this job, I need to return nested JSON which always includes "Grade" and its properties whether "Grade" is null or not.

1 Answers

Simplest solution is to initialize property after materialization:

var students = _dbcontext.Student
    .Include(s => s.Grade)
    .AsNoTracking()
    .ToList();

Grade emptyGrade = null;
foreach(var s in students)
{
   if (s.Grade == null)
   {
      emptyGrade ??= new Grade();
      s.Grade = emptyGrade;
   }
}

Also there is another option with custom projection

var query = 
   from s in _dbcontext.Student
   select new Student
   {
       Id = s.Id,
       Name = s.Name,
       GradeId = s.GradeId,
       grade = s.grade ?? new Grade()
   };

var students = query.ToList();
Related