AutoMapper定义映射级别 [英] AutoMapper define mapping level

查看:81
本文介绍了AutoMapper定义映射级别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class Foo
{
    public string Baz { get; set; }
    public List<Bar> Bars { get; set; }
}

当我映射上面的类时,有什么方法可以定义我想要自动映射器映射对象的深度吗?我需要的一些伪代码:

When I map the class above, is there any way to define how deep I want automapper to map objects? Some pseudo code of what I'm after:

var mapped = Mapper.Map<FooDTO>(foo, opt => { levels: 0 });
// result = { Baz: "" }

var mapped = Mapper.Map<FooDTO>(foo, opt => { levels: 1 });
// result = { Baz: "", Bars: [{ Blah: "" }] }

 var mapped = Mapper.Map<FooDTO>(foo, opt => { levels: 2 });
// result = { Baz: "", Bars: [{ Blah: "", Buzz: [{ Baz: "" }] }] }

// etc...

由于存在nuget依赖性,我当前正在使用automapper 3.3.

I'm currently using automapper 3.3 due to a nuget dependency.

推荐答案

您可以通过在运行时提供值来解决此问题,方法如下:

You can do it by providing a value at runtime as was answered in question: How to ignore a property based on a runtime condition?.

配置:

Mapper.CreateMap<Foo, FooDTO>().ForMember(e => e.Bars,
    o => o.Condition(c => !c.Options.Items.ContainsKey("IgnoreBars")));

用法:

Mapper.Map<FooDTO>(foo, opts => { opts.Items["IgnoreBars"] = true; });

使用相同的配置方法,您可以将所有嵌套的对象都应用到调用的层中.

Same configuration approach you can apply for all your nested objects that you call levels.

如果您想为数据库实体实现相同的行为,则可以按照此答案中的说明使用ExplicitExpansion方法:

If you want to achieve same behavior for your DB Entities you can use ExplicitExpansion approach as described in this answer: Is it possible to tell automapper to ignore mapping at runtime?.

配置:

Mapper.CreateMap<Foo, FooDTO>()
    .ForMember(e => e.Bars, o => o.ExplicitExpansion());

用法:

dbContext.Foos.Project().To<FooDTO>(membersToExpand: d => d.Bars);

这篇关于AutoMapper定义映射级别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆