假设我有以下实体框架代码优先模型:
public class Employee {
[Key]
public int Id { get; set; }
public int DepartmentId { get; set; }
[ForeignKey(nameof(DepartmentId ))]
public Department Department { get; set; }
public DateTime EntryDate { get; set; }
}
public class Manager {
[Key]
public int Id { get; set; }
public int DepartmentId { get; set; }
[ForeignKey(nameof(DepartmentId ))]
public Department Department { get; set; }
}
public class Department {
[Key]
public int Id { get; set; }
[InverseProperty(nameof(Employee.Department))]
public virtual ICollection<Employee> Employees { get; set; }
[InverseProperty(nameof(Manager.Department))]
public virtual ICollection<Manager> Managers { get; set; }
}
以下DTO对象:
public class MyDto {
public int ManagerId { get; set; }
public Employee NewestEmployee { get; set; }
}
我想使用AutoMapper将管理器列表转换为DTO对象列表。 AutoMapper配置如下:
CreateMap<Manager, MyDto>()
.ForMember(
m => m.NewestEmployee,
opt => opt.MapFrom(
manager =>
manager.Department.Employees.OrderBy(employee => employee.EntryDate).FirstOrDefault()))
并且这样称呼:
IEnumerable<Manager> managers = GetAllManagers();
var data = Mapper.Map<IEnumerable<MyDto>>(managers);
虽然这有效,但它会为每个经理向employee表发出单独的SQL语句请求。有没有办法通过只执行一个SQL查询来提高性能(通过更改Entity Framework模型或AutoMapper配置中的某些内容)?