[英]Entity from Entity Framework is supposed to have a populated list, but it's always empty
I'm working on a project for an interview. 我正在为一个面试项目。 My project has an
EmployeeService
class for getting employees from the database. 我的项目有一个
EmployeeService
类,用于从数据库中获取员工。 Employees can have a list of Dependents. 员工可以有一个家属列表。 However, this list is always returning as an empty array.
但是,此列表始终以空数组形式返回。
This is what my entity looks like: 这是我的实体的样子:
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; }
}
This is what my DbContext
class looks like for accessing my database: 这是我的
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; }
}
And here are some relevant methods from my EmployeeService
class. 这是我的
EmployeeService
类中的一些相关方法。 This is the class my controller is using: 这是我的控制器正在使用的类:
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();
}
Now my problem is that my list of dependents is not getting populated. 现在我的问题是我的受抚养者清单没有被填充。 I'm getting an empty array each time from my
DbContext
, and I'm not sure why. 每次我从
DbContext
获得一个空数组,但我不确定为什么。 Both the GetAllEmployees
and GetEmployee
methods always return an empty array of dependents (note, this is not due to that ToDto()
method. I verified that the dependents are empty prior to reaching that point). GetAllEmployees
和GetEmployee
方法总是返回一个空的依赖项数组(请注意,这不是由于该ToDto()
方法。我验证了依赖项在到达该点之前为空)。
Here is a screenshot of the database tables, confirming Anakin should have the one dependent (I'll add Leia later) 这是数据库表的屏幕快照,确认Anakin应该有一个依赖项(我稍后会添加Leia)
But I just get this back: 但是,我只是得到了这个:
{
"dependents": [],
"id": 1,
"firstName": "Anakin",
"lastName": "Skywalker"
},
you need to add .Include(x => x.Dependents)
您需要添加
.Include(x => x.Dependents)
return _dbContext.Employees.Include(x => x.Dependents).ToList();
PS: try by not using .Select statement since it breaks Inclusion. PS:尝试不使用.Select语句,因为它会破坏包含。
I Advise you to use mapper for mapping source class to destination class dto. 我建议您使用映射器将源类映射到目标类dto。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.