【问题标题】:Entity Framework: object returns with an empty list at first, but then suddenly the list is populated correctly实体框架:对象首先返回一个空列表,但随后列表突然被正确填充
【发布时间】:2020-06-07 00:30:15
【问题描述】:

我有以下课程:

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)

});

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

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】:

另外,我不明白为什么在一种情况下会填充列表,而在另一种情况下则根本不填充。

这是实体框架中的Lazy Loading 功能。延迟加载是指延迟加载相关数据,直到您明确要求。如需更多解释和深入了解,您可以查看this good article

Entity Framework supports three ways to load related data - 急切加载、延迟加载和显式加载。对于您的场景,它更喜欢使用急切的加载方式。为了实现这个目标,EF 有Include() 方法。所以,你可以更新你的 GetById 方法如下:

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

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

【讨论】:

  • 谢谢,它现在确实按预期工作了。我仍然不明白为什么在我的上一个示例中(在控制器中调用端点)它会返回一个很难的 empy 列表。为什么在 HttpResponse 中返回列表不触发加载?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多