我正在开发一个使用 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/