[实体框架:对象返回时最初带有空列表,但随后突然将其正确填充]

问题描述 投票:0回答:1

我有以下课程:

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

   //other properties

   public User()
   {
    Connections = new List<User>();
   }
}

然后我有一个用于存储的DataContext类:

 public class DataContext : DbContext
 {
     public DataContext() { }

     public DataContext(DbContextOptions<DataContext> options) : base(options) { }

     public virtual DbSet<User> Users { get; set; }
 }

和一个UserService类:

public class UserService: IUserService
{
   private DataContext _context;

   public UserService(DataContext context)
   {
      _context = context;
   }

   public User GetById(int id)
   {
      return _context.Users.Find(id);
   }
   ...
}

现在假设我正确存储了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

我读过它可能与循环依赖有关,但是我没有得到任何例外。

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

知道是什么原因造成的吗?

c# entity-framework linq .net-core circular-dependency
1个回答
1
投票

而且我也不明白为什么在一种情况下会在列表之后填充列表,而在另一种情况下却根本不填充列表。

这是实体框架中的Lazy Loading功能。延迟加载意味着delaying加载相关数据,直到您明确要求为止。有关更多说明和深入探讨,请查看this good article

Entity Framework supports three ways to load related data-渴望加载,延迟加载和显式加载。对于您的方案,它更倾向于使用预加载方式。为了实现这一目标,EF采用了Include()方法。因此,您可以按以下方式更新Include()方法:

GetById

使用上述查询,当您找到特定用户时,其连接也会同时加载。祝你好运。

© www.soinside.com 2019 - 2024. All rights reserved.