自动映射和深度加载

时间:2012-05-06 05:37:34

标签: automapper

关于自动化已经“深度加载”的实体框架对象,我有一个问题。我有一个Project对象,它有一个名为Tasks的成员,它是一个集合。每个任务都有一个名为Works的成员,它是一个集合。深度加载项目时,这些任务及其Works成员都已填充。它看起来像这样:

-- Project
    -- Task 1
        -- Work 1
        -- Work 2
    -- Task 2
        -- Work 3

我已经想出了如何使用这样的解析器来深度绘制1级:

CreateMap<DataAccess.Task, Entities.Task>()
            .ForMember(obj => obj.Description, obj => obj.MapFrom(src => src.Description))
            .ForMember(obj => obj.Estimate, obj => obj.MapFrom(src => src.Estimate))
            .ForMember(obj => obj.Id, obj => obj.MapFrom(src => src.ID))
            .ForMember(obj => obj.ProjectId, obj => obj.MapFrom(src => src.Project))
            .ForMember(obj => obj.TaskName, obj => obj.MapFrom(src => src.TaskName))
            .ForMember(obj => obj.Visible, obj => obj.MapFrom(src => src.Visible))
            .ForMember(obj => obj.WorkItems, obj => obj.ResolveUsing<WorkItemsResolver>().FromMember(src => src.Works));

public class WorkItemsResolver : ValueResolver<EntityCollection<DataAccess.Work>, ICollection<Entities.Work>>
{
    #region Overrides of ValueResolver<List<Task>,List<Task>>

    protected override ICollection<Entities.Work> ResolveCore(EntityCollection<DataAccess.Work> source)
    {
        Mapper.EntitiesMapper entitiesMapper = new EntitiesMapper(); 
        return source.Select(wk => entitiesMapper.Map<Entities.Work>(wk)).ToList();
    }

    #endregion
}

然而,我无法弄清楚如何深入2级,即能够映射顶级对象(Project)并让它的子列表(及其子列表)也映射到它们的伴随业务对象。

有人知道Automapper是否可以这样做吗?

由于

1 个答案:

答案 0 :(得分:2)

每个Entity对象都应该有一个相应的DataAccess对象。您已经有了一个任务映射,现在需要一个Work。另外,不要使用单独的ValueResolvers。您可以使用ForMember中的lambda重载执行任何操作。

CreateMap<DataAccess.Task, Entities.Task>()
    // when names match on both sides, there is no need to call ForMember
    //.ForMember(obj => obj.Description, obj => obj.MapFrom(src => src.Description))
    //.ForMember(obj => obj.Estimate, obj => obj.MapFrom(src => src.Estimate))
    //.ForMember(obj => obj.Id, obj => obj.MapFrom(src => src.ID))
    .ForMember(obj => obj.ProjectId, obj => obj.MapFrom(src => src.Project))
    //.ForMember(obj => obj.TaskName, obj => obj.MapFrom(src => src.TaskName))
    //.ForMember(obj => obj.Visible, obj => obj.MapFrom(src => src.Visible))
    .ForMember(obj => obj.WorkItems, obj => obj.ResolveUsing(src =>
        Mapper.Map<IEnumerable<DataAccess.Work>>(src.Works)))
;

CreateMap<DataAccess.Work, Entities.Work>()
    // only call ForMember on properties that don't map automatically
;

由于您在对象层次结构中为2的深度级别创建了一个地图,因此您可以在ResolveUsing lambda重载中调用Mapper.Map。