首页 > 解决方案 > Automapper:将此设置为属性

问题描述

是否可以使用 AutoMapper 做到这一点:将源对象放在目标对象的私有属性中。

在我想做的情况下:

using System;
using System.Diagnostics;
using AutoMapper;

namespace ConsoleApp12 {

    class B {
        public B() { }
    }

    class A {
        public B B { get; private set; }
        public A() { }
    }

    class Program {
        static void Main(string[] args) {
            var config = new MapperConfiguration(cfg =>
                 cfg.CreateMap<B, A>()
                    .ForMember(ma => ma.B, mb => mb) //Error mb can't be "this"
            );
            var mapper = new Mapper(config);

            var b = new B();
            var a = mapper.Map<A>(b);

            Debug.Assert(a.B != null);
        }
    }
}

标签: c#automapper

解决方案


我认为您在成员映射中需要稍微不同的语法。

请注意,第二个参数不是您要映射的值,而是通过 MapFrom 表达的如何获取该值的表达式。

我更改了 lambda 表达式参数以使其更易于阅读,并添加了一个虚拟属性来证明这一点。

void Main()
{
}



class B
{
    public int MyProperty { get; set; }
    public B() { }
}

class A
{
    public B B { get; private set; }
    public A() { }
}

class Program
{
    static void Main(string[] args)
    {
        var config = new MapperConfiguration(cfg =>
        {
            cfg.CreateMap<B, A>()
               .ForMember(dest => dest.B, opt => opt.MapFrom(src => src));
        });
        var mapper = new Mapper(config);

        var b = new B() { MyProperty = 123 };
        var a = mapper.Map<A>(b);

        config.AssertConfigurationIsValid();

        Debug.Assert(a.B != null);

        Debug.Assert(a.B.MyProperty == 123);

    }
}
``

推荐阅读