将数据模型映射到域模型

时间:2015-08-19 14:37:26

标签: entity-framework asp.net-mvc-5 lazy-loading automapper

我目前正在使用AutoMapper将我的数据模型映射到我的域模型,但这会导致性能问题。在我的存储库中,我懒得加载员工记录。在我的存储库中,当我得到员工的一切都是正确的,但是当我返回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();
    }

1 个答案:

答案 0 :(得分:2)

问题不在于AutoMapper可能你已经配置了ef来选择相关的实体,所以这可能是一个问题,要在dbcontext构造函数中添加base.Configuration.LazyLoadingEnabled = false;来解决这个问题。

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

此致