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

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


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();