我们如何在automapper中为同一个实体创建不同的映射

时间:2017-02-17 18:53:39

标签: c# entity-framework automapper

我需要将实体的映射写入其DTO以用于列出目的和详细实体视图。但是对于列表我需要忽略一个列表属性,因为我不想加载它,我已经在实体框架中启用了延迟加载。在查询列表视图的数据时,如何创建同一实体的两个映射或为属性添加ignore。

cfg.CreateMap<page, PageViewModel>().ForMember(t => t.PageRows, opts => opts.MapFrom(s => s.page_rows)).
            ForMember(t => t.PageRules, opts => opts.MapFrom(s => s.page_rules.Select(x => x.rule_id)));
cfg.CreateMap<page, PageViewModel>().ForMember(t => t.PageRows, opts => opts.Ignore()).
            ForMember(t => t.PageRules, opts => opts.MapFrom(s => s.page_rules.Select(x => x.rule_id)));

2 个答案:

答案 0 :(得分:2)

您可以使用Precondition设置Func<ResolutionContext, bool>,然后使用Map方法重载Action<IMappingOperationOptions>来通过Items字典传递控制参数。

例如:

.ForMember(t => t.PageRows, opts => 
{
     opts.MapFrom(s => s.page_rows);
     opts.PreCondition(context => !context.Items.ContainsKey("IgnorePageRows"));
})

然后:

IEnumerable<page> source = ...;
var withPageRows = Mapper.Map<List<PageViewModel>>(source);
var noPageRows = Mapper.Map<List<PageViewModel>>(source, 
    opts => opts.Items.Add("IgnorePageRows", null));

参考:Conditional mapping

答案 1 :(得分:1)

您必须创建两个不同的DTO类才能映射到。如果您不想这样做,您还可以选择创建两个标记接口并映射到这些接口。