簡體   English   中英

實體框架中的實體應該具有填充列表,但始終為空

[英]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獲得一個空數組,但我不確定為什么。 GetAllEmployeesGetEmployee方法總是返回一個空的依賴項數組(請注意,這不是由於該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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM