【问题标题】:Can't Include navigation property (it is null) [duplicate]不能包含导航属性(它为空)[重复]
【发布时间】:2023-03-29 12:50:02
【问题描述】:

我正在尝试从数据库中获取学生,还包括与他们对应的课程实体,但似乎我做错了什么。

这是学生班:

public class Student
{
    public int StudentID { get; set; }

    public string Name { get; set; }

    public int CourseID { get; set; }  

    public virtual Course Course { get; set; }
}

这是课程:

public class Course
{
    public int CourseID { get; set; }

    public string Name { get; set; }

    public virtual ICollection<Student> Students { get; set; }
}

然后我检索学生实体的集合,如下所示:

context.Students.Include(i => i.Course).ToList();

如果我删除了 include 方法,那么我会得到数据,但是 student 对象的 course 属性是 null。

P.S 我正在使用 Postman 进行测试,使用“包含”我无法得到任何东西。

如果我对此发表评论

public virtual ICollection<Student> Students { get; set; }

一切正常。

我把完整代码放在github上:

https://github.com/AlexDev5/Problem

【问题讨论】:

  • 我的意思是postman中显示数据“无法得到任何响应”

标签: asp.net-web-api entity-framework-core


【解决方案1】:

您必须将序列化程序配置为忽略项目中的循环引用。

因此,为此您必须在 ConfigureServices 方法中添加以下代码行 Startup.cs

喜欢

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc()
    .AddJsonOptions(options => {
        options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
    });
}

【讨论】:

  • 我想,我的情况有点不同。在旧版本中,我也没有问题..
  • @A.M.,查看图片中的结果。
  • 您是否在使用 Entity Framework 核心的 ASP.NET Core WEB API 2 中对其进行测试?也许有区别
  • 我有一个 web api 不是核心的项目,它运行良好
  • 你在web api core中使用吗?
【解决方案2】:

取决于在此处找到的示例https://github.com/aspnet/EntityFramework.Docs/tree/master/samples/core/Querying/Querying

我写了一个解决方案,但我不知道它是否是解决这个问题的好方法:

我创建了 StudentCourse 类并定义如下:

public class StudentCourse
{
    public int StudentCourseID { get; set; }

    public int StudentID { get; set; }
    public Student Student{ get; set; }

    public int CourseID { get; set; }
    public Course Course { get; set; }
}

我修改了 Course 类,如下所示:

public class Course
{
    public int CourseID { get; set; }

    public string Name { get; set; }

    public virtual ICollection<StudentCourse> Students { get; set; }
}

【讨论】:

  • 但这与附加链接表完全不同(多对多)关系。而原始设计是一对多的。 Include 应该在这两种情况下都能正常工作,除非您的数据库架构与模型不匹配。
  • @Ivan Stoev,我在调试模式下对其进行了多次测试,当调试器在public virtual ICollection&lt;Student&gt; Students { get; set; } 中访问get 时出现问题。所以,如果我删除这行代码,问题就会消失..
  • 我已经把源代码放到了github上...github.com/AlexDev5/Problem
  • “如果我从 Course 类中删除“Students”虚拟属性,我会得到我需要的。” - 那么你的问题与 EF Core 无关,但是具有循环引用的对象的 Json 序列化。这里有很多关于如何配置 Json 引用循环处理的帖子。例如,我标记为重复的那个。
  • 谢谢,我会读一读...
猜你喜欢
  • 2015-12-23
  • 1970-01-01
  • 2020-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多