简体   繁体   English

我们如何在自动映射器中为同一实体创建不同的映射

[英]How can we create different mapping for same entity in automapper

I need to write mapping for an entity to its DTO for listing purpose and details view of an entity. 我需要将实体映射到其DTO,以用于列出目的和实体的详细信息视图。 But for listing I need to ignore a list property because of DTO because I don't want to load it, I have enabled Lazy loading in Entity framework. 但是对于列表,由于DTO因为我不想加载它,因此我需要忽略一个列表属性,因为我已经在实体框架中启用了延迟加载。 How can I create two mappings of same entity or add ignore for a property while querying data for list view. 在查询列表视图数据时,如何创建两个相同实体的映射或为属性添加忽略。

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)));

You can setup a Precondition with Func<ResolutionContext, bool> and then use the Map method overloads with Action<IMappingOperationOptions> to pass the controlling parameter through Items dictionary. 您可以使用Func<ResolutionContext, bool>设置Precondition ,然后将Map方法重载与Action<IMappingOperationOptions>以将控制参数传递给Items字典。

For instance: 例如:

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

and then: 接着:

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

Reference: Conditional mapping 参考: 条件映射

You would have to create two different DTO classes to map to. 您将必须创建两个不同的DTO类进行映射。 If you do not want to do that, you also have another option which would be to create two marker interfaces and map to those. 如果您不想这样做,那么您还可以选择创建两个标记器接口并映射到那些标记器接口。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM