我正在使用 objectDataSource 来填充 gridview 。我有2个简单的课程:
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”), gridview 中也缺少员工。我在这做错了什么?
答案 0 :(得分:0)
首先,您需要在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);
}
}
- 或 -
将 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; }
}
仅供参考:您希望使用虚拟,以防将来有人想要使用延迟加载。
答案 1 :(得分:0)
return employeeDBContext.Departments.Include(x =>x.Employees ).ToList();
?