[英]Entity from Entity Framework is supposed to have a populated list, but it's always empty
我正在为一个面试项目。 我的项目有一个EmployeeService
类,用于从数据库中获取员工。 员工可以有一个家属列表。 但是,此列表始终以空数组形式返回。
这是我的实体的样子:
public class Employee : Person
{
public ICollection<Dependent> Dependents { get; set; } = new List<Dependent>();
}
public class Person
{
[Key]
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
这是我的DbContext
类用于访问数据库的样子:
public class AppDbContext : DbContext, IAppDbContext
{
public AppDbContext(DbContextOptions options) : base(options)
{
}
public AppDbContext()
{
}
public virtual DbSet<Employee> Employees { get; set; }
public virtual DbSet<Pay> PayEntries { get; set; }
public virtual DbSet<Dependent> Dependents { get; set; }
}
这是我的EmployeeService
类中的一些相关方法。 这是我的控制器正在使用的类:
public ICollection<EmployeeDto> GetAllEmployees()
{
return _dbContext.Employees.Select(e => e).ToList().Select(e => e.ToDto()).ToList();
}
public EmployeeDto GetEmployee(int id)
{
var employee = _dbContext.Employees.FirstOrDefault(e => e.Id == id);
if (employee == null)
throw new Exception("Employee does not exist");
return employee.ToDto();
}
现在我的问题是我的受抚养者清单没有被填充。 每次我从DbContext
获得一个空数组,但我不确定为什么。 GetAllEmployees
和GetEmployee
方法总是返回一个空的依赖项数组(请注意,这不是由于该ToDto()
方法。我验证了依赖项在到达该点之前为空)。
这是数据库表的屏幕快照,确认Anakin应该有一个依赖项(我稍后会添加Leia)
但是,我只是得到了这个:
{
"dependents": [],
"id": 1,
"firstName": "Anakin",
"lastName": "Skywalker"
},
您需要添加.Include(x => x.Dependents)
return _dbContext.Employees.Include(x => x.Dependents).ToList();
PS:尝试不使用.Select语句,因为它会破坏包含。
我建议您使用映射器将源类映射到目标类dto。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.