【问题标题】:Entity Framework Core: How to include a null related Entity with its null column properties?实体框架核心:如何包含具有空列属性的空相关实体?
【发布时间】:2021-02-22 13:21:10
【问题描述】:

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

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

我的 LINQ 像这样渴望加载学生

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

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

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

    • 也许 var emptyGrade = new Grade(); ?
    • 或者 var emptyGrade = new Grade { StudentGrade ="No Grade"}; ?
    • @Sergey 为什么要引入不必要的分配?
    • 我喜欢这个答案。 @MTLC,我认为这个答案的一个关键点是,为 JSON 塑造对象并不是真正的 EF(存储)问题,并且可以在读取 EF 对象后完成,这有助于保持层分离。
    • foreach(var s in students) s.Grade ??= new Grade() 就足够了。
    猜你喜欢
    • 2021-12-04
    • 1970-01-01
    • 1970-01-01
    • 2020-03-02
    • 1970-01-01
    • 2013-09-06
    • 2021-06-06
    • 1970-01-01
    • 2021-06-19
    相关资源
    最近更新 更多