c# - Entity Framework 核心 : How to include a null related Entity with its null column properties?

标签 c# json asp.net-core entity-framework-core

我正在开发一个使用 EF Core 和 .Net Core 的项目。

我有 2 个实体类。它们是一对多的关系。假设 '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;}
}

我的 LINQ to eager load student 是这样的

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

有时,我创建了一条“学生”记录,但没有为其设置“成绩”。结果,Grade 将为空。由于我将 WebAPI 用于这项工作,因此我需要返回嵌套的 JSON,它始终包含“Grade”及其属性,无论“Grade”是否为 null。

最佳答案

最简单的解决方案是在物化后初始化属性:

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

另外还有一个自定义投影的选项

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

关于c# - Entity Framework 核心 : How to include a null related Entity with its null column properties?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66316514/

相关文章:

c# - 如何使用 C# 在 Winforms 中强制控制触发离开事件?

c# - wpf 数据绑定(bind)不从属性更新

json - 金青 |更新 `select` 选择的数组元素

C# PDF 删除 - 文件 'being used by another process'

c# - 统一错误 : Setting the parent of a transform which resides in a prefab is disabled to prevent data corruption

iPhone 通过 POST 发送 Json 数组

javascript - 从表单构建 JSON 对象

asp.net-core - 无法从 System.security.claims.claimsPrincipal 转换为 Scheduler.Areas.Identity.Data

c# - 部署具有 MSI 的容器实例并且部署到该实例的容器无法读取 keyvault secret

c# - Docker Volume 中的写入权限