是否可以使用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);
}
}
}
我认为您在成员映射中需要稍微不同的语法。
请注意,第二个参数不是您要映射的值,而是通过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);
}
}
``