未加载导航属性

本文关键字:属性 导航 加载 | 更新日期: 2023-09-27 17:57:28

我正在使用对象数据源来填充网格视图。我有两个简单的类:

public class Employee
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Gender { get; set; }
    public int Salary { get; set; }
    public Department Department { get; set; }
}

public class Department
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Location { get; set; }
    public List<Employee> Employees { get; set; }
}

我也有

public class EmployeeDBContext : DbContext
{
    public DbSet<Department> Departments { get; set; }
    public DbSet<Employee> Employees { get; set; }
}

现在在我的EmployeeRepository课上,我有

public List<Department> GetDepartments()
{
    EmployeeDBContext employeeDBContext = new EmployeeDBContext();
    return employeeDBContext.Departments.Include("Employees").ToList();
}

尽管我添加了.Include("Employees"),但网格视图中缺少这些员工。我在这里做错了什么?

未加载导航属性

首先,您需要在Employee类中有一个外键(DepartmentId)<我不知道视频是怎么逃脱惩罚的>

public class Employee
{
    public int Id { get; set; }
    public int DepartmentId { get; set; } <=====
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Gender { get; set; }
    public int Salary { get; set; }
    public virtual Department Department { get; set; }
           ^^^^^^^
}
public class Department
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Location { get; set; }
    public virtual ICollection<Employee> Employees { get; set; }
           ^^^^^^^^^^^^^^^^^^
}
public partial class EmployeeDBContext : DbContext
{
    public virtual DbSet<Employee> Employee { get; set; }
    public virtual DbSet<Department> Department { get; set; }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        // Optional, but good practice to have the mapping here. 
        modelBuilder.Entity<Department>()
            .HasMany(e => e.Employee)
            .WithRequired(e => e.Department)
            .HasForeignKey(e => e.DepartmentId);
    }
}

-OR-

DepartmentId属性和[ForeignKey]数据注释添加到Department。

public class Employee
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Gender { get; set; }
    public int Salary { get; set; }    
    public int DepartmentId { get; set; } <=== 
    // Optional, but good practice to have this data annotation attribute. 
    [ForeignKey("DepartmentId")] <=== 
    public Department Department { get; set; }
}

仅供参考:你想使用虚拟,以防将来有人想使用延迟加载

你试过这样的吗

return employeeDBContext.Departments.Include(x =>x.Employees ).ToList();