将数据模型映射到领域模型

Mapping Data Model to Domain Model

我目前正在使用 AutoMapper 将我的数据模型映射到我的域模型,但它导致了性能问题。在我的存储库中,我懒加载员工记录。当我得到员工时在我的存储库中一切都是正确的,但是当我 return employee.ToDomain() AutoMapper 导致加载 Employee 的所有属性时,导致多个查询被发送到导致页面需要几分钟才能加载的数据库。有没有办法防止这种情况发生,或者我不应该在数据访问层中使用 AutoMapper 来映射到域模型?

存储库:

public Employee GetEmployee(int employeeId)
{
    EfModels.Employee employee = Context.Employees
                    .SingleOrDefault(e => e.EmployeeId == employeeId);

    return employee != null ? employee.ToDomain() : null;
}

员工:

public class Employee : BaseModel
{
    ...
    public Domain.Models.Employee ToDomain()
    {
        return Mapper.Map<Domain.Models.Employee>(this);
    }
}

更新

地图:

Mapper.CreateMap<EfDataAccess.EfModels.Employee, Employee>()
            .ForMember(dto => dto.Division, conf => conf.MapFrom(e => e.Division.DivisionName))
            .ForMember(dto => dto.EducationType, conf => conf.MapFrom(e => e.EducationType.Education))
            .ForMember(dto => dto.EEOJobCategory, conf => conf.MapFrom(e => e.EEOJobCategory.EEOJobCategoryName))
            .ForMember(dto => dto.EmployeeStatus, conf => conf.MapFrom(e => e.EmployeeStatus.EmployeeStatusName))
            .ForMember(dto => dto.GenderType, conf => conf.MapFrom(e => e.GenderType.Gender))
            .ForMember(dto => dto.JobTitle, conf => conf.MapFrom(e => e.JobTitle.JobTitleName))
            .ForMember(dto => dto.NationalOriginType, conf => conf.MapFrom(e => e.NationalOriginType.NationalOrigin))
            .ForMember(dto => dto.OfficeLocation, conf => conf.MapFrom(e => e.OfficeLocation.Location))
            .ForMember(dto => dto.PositionNumber, conf => conf.MapFrom(e => e.PositionNumber.Number))
            .ForMember(dto => dto.RaceType, conf => conf.MapFrom(e => e.RaceType.Race))
            .ForMember(dto => dto.TransactionType, conf => conf.MapFrom(e => e.TransactionType.Transaction))
            .ForMember(dto => dto.WorkScheduleType, conf => conf.MapFrom(e => e.WorkScheduleType.ScheduleNumberType))
            .ReverseMap();

存储库:

public Employee GetEmployee(int employeeId)
    {
        return Context.Employees
            .Where(e => e.EmployeeId== e.employeeId)
            .Project().To<Employee>().FirstOrDefault();
    }

问题不在于 AutoMapper,也许您已将 ef 配置为 select 相关实体,因此这可能是一个问题,要解决此问题,请在您的 dbcontext 构造函数中添加 base.Configuration.LazyLoadingEnabled = false;

我看到的另一个不好的部分是你首先咨询了雇员(在这里,你返回了所有有雇员的字段)然后进行映射,为了解决这个问题,请 select 只有字段您需要或使用自动映射器的投影功能:https://github.com/AutoMapper/AutoMapper/wiki/Queryable-Extensions

此致,