C# 实体框架:对象首先返回一个空列表,但突然列表被正确填充

C# 实体框架:对象首先返回一个空列表,但突然列表被正确填充,c#,entity-framework,linq,.net-core,circular-dependency,C#,Entity Framework,Linq,.net Core,Circular Dependency,我有以下课程: public class User { public int Id { get; set; } public List<User> Connections { get; set; } //other properties public User() { Connections = new List<User>(); } } 现在假设我正确地存储了2个用户,并将它们添加到各自的连接列表中 问题出在以下代码中:

我有以下课程:

public class User
{
   public int Id { get; set; }
   public List<User> Connections { get; set; }

   //other properties

   public User()
   {
    Connections = new List<User>();
   }
}
现在假设我正确地存储了2个用户,并将它们添加到各自的连接列表中

问题出在以下代码中:

var user1 = _userService.GetById(userId);

 ---> Here user1.Connections is an empty list (unexpected)

var results = anotherList.Select(x=> 
{

   ---> Here user1.Connections have one object inside (the other user as expected)

});

我认为这是因为列表尚未填充,因为它从未被访问过,但我在控制器中的以下端点也有问题:

var userId = int.Parse(User.Identity.Name);

var user1 = _userService.GetById(userId);

var connectionsInfo = user1.Connections.Select(x => new
{
   Id = x.Id,
   //map other properties
});

return Ok(connectionsInfo);
//this time an empty list is returned in the response, instead of a list with a single object
我读到它可能是关于循环依赖,但我没有得到任何例外

另外,我不明白为什么在一种情况下,列表是在之后填充的,而在另一种情况下,列表根本没有填充

你知道这是什么原因吗

我也不明白为什么在一种情况下,列表是在之后填充的,而在另一种情况下,根本没有填充

这是实体框架中的
延迟加载
特性。延迟加载意味着延迟相关数据的加载,直到您明确请求为止。要获得更多解释和深入了解,您可以回顾

-即时加载、延迟加载和显式加载。对于您的场景,它更喜欢使用渴望加载方式。为了实现这一目标,EF有方法。因此,您可以更新
GetById
方法,如下所示:

public User GetById(int id)
{
   return _context.Users
             .Include(item => item.Connections)
             .Find(id);
}
通过上面的查询,当您找到一个特定的用户时,它的连接也会同时加载。祝你好运

我也不明白为什么在一种情况下,列表是在之后填充的,而在另一种情况下,根本没有填充

这是实体框架中的
延迟加载
特性。延迟加载意味着延迟相关数据的加载,直到您明确请求为止。要获得更多解释和深入了解,您可以回顾

-即时加载、延迟加载和显式加载。对于您的场景,它更喜欢使用渴望加载方式。为了实现这一目标,EF有方法。因此,您可以更新
GetById
方法,如下所示:

public User GetById(int id)
{
   return _context.Users
             .Include(item => item.Connections)
             .Find(id);
}

通过上面的查询,当您找到一个特定的用户时,它的连接也会同时加载。祝你好运。

可能需要使用。使用Include…,但这可能是循环依赖项的问题。可能需要使用。使用Include…,但这可能是循环依赖项的问题。谢谢,它现在确实可以正常工作。我仍然不明白为什么在我的上一个示例中(调用控制器中的端点),它返回empy列表。为什么在HttpResponse中返回列表不会触发加载?谢谢,它现在确实按照预期工作。我仍然不明白为什么在我的上一个示例中(调用控制器中的端点),它返回empy列表。为什么在HttpResponse中返回列表不会触发加载?
public User GetById(int id)
{
   return _context.Users
             .Include(item => item.Connections)
             .Find(id);
}