【发布时间】:2018-12-14 15:01:10
【问题描述】:
我正在做一个面试项目。我的项目有一个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"
},
【问题讨论】:
标签: c# entity-framework