简体   繁体   English

实体框架核心:如何包含 null 相关实体及其 null 列属性?

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

I'm working on a project which uses EF Core and.Net Core.我正在开发一个使用 EF Core 和 .Net Core 的项目。

I have 2 Entity classes.我有 2 个实体类。 They are one-to-many relationships.它们是一对多的关系。 Let say 'Student' N <-----> 1 'Grade'.假设'学生' N <-----> 1 '等级'。

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我的 LINQ 像这样急切地加载学生

_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.结果,等级将为 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.由于我使用 WebAPI 来完成这项工作,我需要返回嵌套的 JSON ,它始终包括“等级”及其属性,无论“等级”是否为 null。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM