1

我有一个关于自动映射“深度加载”的实体框架对象的问题。我有一个 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 层,即能够映射顶级对象(项目)并让它的子列表(及其子列表)也映射到它们的伴随业务对象。

有谁知道 Automapper 是否可以做到这一点?

谢谢

4

1 回答 1

2

每个 Entity 对象都应该有一个对应的 DataAccess 对象。您已经有一个任务映射,现在您需要一个用于工作。此外,不要使用单独的 ValueResolver。您可以使用 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。

于 2012-05-15T07:35:56.973 回答