【发布时间】: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
我读到它可能是关于循环依赖的,但我没有得到任何例外。
另外,我不明白为什么在一种情况下会填充列表,而在另一种情况下则根本不填充。
知道是什么原因造成的吗?
【问题讨论】:
-
可能需要使用loading related entities。
-
使用包含...但这可能是循环依赖的问题。
标签: c# entity-framework linq .net-core circular-dependency