【问题标题】:Entity from Entity Framework is supposed to have a populated list, but it's always empty实体框架中的实体应该有一个填充列表,但它总是空的
【发布时间】: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 得到一个空数组,我不知道为什么。 GetAllEmployeesGetEmployee 方法总是返回一个空的依赖数组(注意,这不是因为 ToDto() 方法。我在到达那个点之前验证了依赖是空的)。

这是数据库表的屏幕截图,确认 Anakin 应该有一个依赖项(我稍后会添加 Leia)

但我只是得到了这个:

{
    "dependents": [],
    "id": 1,
    "firstName": "Anakin",
    "lastName": "Skywalker"
},

【问题讨论】:

    标签: c# entity-framework


    【解决方案1】:

    您需要添加.Include(x =&gt; x.Dependents)

    return _dbContext.Employees.Include(x => x.Dependents).ToList();
    

    PS:尝试不要使用 .Select 语句,因为it breaks Inclusion.

    我建议您使用映射器将源类映射到目标类 dto。

    【讨论】:

    • 我会试试的,谢谢。我不确定你所说的选择打破包容是什么意思,所以我会查一下。哦,我想问一下(因为这是面试),我正在使用 automapper 映射到 DTO,但我是通过扩展方法使用它(ToDto())。我应该采取不同的做法吗?
    • 如果你先发出 .ToList() 然后 .Select(x =&gt; x.ToDto()) 不会有问题。在将其转换为 ToList 之前,您的语句是 Query (IQueryable)。发出 ToList 后,您的查询将在数据库上执行。无论您在 .ToList 之后选择什么,都不会导致任何故障
    • 我参考了我的答案。请检查一下
    • 我不同意你不应该使用 Select。如果您有 ID 为 4 的 Employee,并且它有 1000 个 Dependants,那么每个 Dependent 都将具有具有相同值 4 的外键 EmployeeId。发送该值 1001 次是一种浪费。我的建议是:始终使用 Select 并仅选择您实际计划使用的属性。使用 include 的唯一原因是您计划更新包含的项目。
    • 我建议仅用于这种情况。当然,使用 select 有很多好处。您是否跟踪过 OP 代码?他的第一个选择打破了包容性。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-26
    • 2013-08-09
    相关资源
    最近更新 更多